1

I want to convert "1 1/2" in JavaScript so that when I say print x (where x = "1 1/2") it returns 1.5.

Currently while using the following 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;
}

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

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.

For example

  1. 1/2 Teaspoon of Salt
  2. 1 1/2 Teaspoon of Chilli Powder
  3. 2.5 Teaspoon of garlic powder
  4. 2 Teaspoon of cream-style horseradish

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.

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.

I got this working with the above code. Thanks @Rocket for the idea

Sukhjinder Singh
  • 1,745
  • 2
  • 19
  • 26

1 Answers1

4

You can use eval (if you can trust where the string is coming from).

console.log(eval('1/2')); // 0.5
console.log(eval('1.5')); // 1.5

Or, you can split the string on the /.

var x = '1/2';

var y = x.split('/');
if(y.length > 1){
    console.log(y[0] / y[1]);
}
else{
    console.log(y[0]);
}

UPDATE: Handling mixed numbers, such as 1 1/2 will take a little more parsing. Besides splitting on the /, we need to split on the space.

var x = '1 1/2';

var y = x.split(' ');
if(y.length > 1){
    var z = y[1].split('/');
    console.log(+y[0] + (z[0] / z[1]));
}
else{
    var z = y[0].split('/');
    if(z.length > 1){
        console.log(z[0] / z[1]);
    }
    else{
        console.log(z[0]);
    }
}​
gen_Eric
  • 223,194
  • 41
  • 299
  • 337