How to convert fraction to float in javascript?
<p>I want to convert <code>"1 1/2"</code> in JavaScript so that when I say print x (where <code>x = "1 1/2"</code>) it returns <code>1.5</code>.</p>

<p>Currently while using the following code</p>

<pre><code>var value = $('#ingredients-1-quantity').val();
var fraction = Number(value);
if(isNaN(fraction)) {
 if(hasFraction = parseFrac(value)) {
  $('#ingredients-1-quantity-hidden').val(hasFraction);
 }
 else {
  $('#ingredients-1-quantity').val('');
  $('#ingredients-1-quantity-hidden').val('');
 }
}

function parseFrac(frac) {
 frac = frac.split(/ ?(\d+)\/(\d+)/);
 if(!isNaN(parseInt(frac[2])))
   return Math.round(frac[0] * 1 + frac[1] / frac[2], 3);
 else
   return false;
}
</code></pre>

<p>Also the code should take care of integer and float values. For example if I say print <code>1</code> OR print <code>1.5</code> it will return as it is.</p>

<p>I am elaborating more. I have a Ingredient form where I am providing text-field, where user will provide Quantity of food under it. This can be float, integer or fraction. </p>

<p>For example</p>

<ol>
<li><strong>1/2</strong> Teaspoon of Salt</li>
<li><strong>1 1/2</strong> Teaspoon of Chilli Powder</li>
<li><strong>2.5</strong> Teaspoon of garlic powder</li>
<li><strong>2</strong> Teaspoon of cream-style horseradish</li>
</ol>

<p>if user is providing value in float or integer that is fine but if user is providing value in fraction than I have convert it into float. </p>

<p>On the view page it is fine to show the quantity as it is (entered by user) but for internal use I have to keep the fraction as float.</p>

<p>I got this working with the above code. Thanks @Rocket for the idea</p>
