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/2 Teaspoon of Salt
- 1 1/2 Teaspoon of Chilli Powder
- 2.5 Teaspoon of garlic powder
- 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