Easy Java Script Code to Convert Mixed Number to Decimal
By Stephen Bucaro
A recent application required code to calculate how many cubic yards of mulch it
would require to cover X square feet of garden area with Y inches of mulch. An
important step in designing such an application is to predict what kind of data
a users might enter into the input form. For example, what if a user wanted to
mulch to a depth of 3 3/4 inches? Wouldn't it be convenient if the user was
allowed to actually enter 3 3/4, rather than having to mentally convert to 3.75?
A number such as 3 3/4 is called a "mixed" number, that is, it contains a whole
part and a fractional part. As far as I know, there are no built-in Java Script
functions that handle mixed numbers. So lets design one.
function toDecimal(s)
{
var StrIn = s;
var depth;
if(StrIn.indexOf("/") > -1)
{
if(StrIn.indexOf(" ") > -1)
{
var whole = StrIn.slice(0, StrIn.indexOf(" "));
var fract = StrIn.slice(StrIn.indexOf(" ") + 1, StrIn.length);
var num = fract.slice(0, fract.indexOf("/"));
var den = fract.slice(fract.indexOf("/") + 1, fract.length);
depth = parseInt(whole) + num/den;
}
else
{
var num = StrIn.slice(0, StrIn.indexOf("/"));
var den = StrIn.slice(StrIn.indexOf("/") + 1, StrIn.length);
depth = num/den;
}
}
else
{
depth = StrIn;
}
return depth;
}
This calculator is designed to accept both decimal and mixed number input, so the
first thing we need to do is determine which format the user entered. The first
if statement in the code looks for a forward slash "/" in the input string,
indicating that the input string contains a fraction. If there is no forward slash,
the user entered a decimal number, so we just return that data.
If the user entered a mixed number, the second if statement looks for the
blank character between the whole number and the fraction part of the mixed number.
If there is no blank character in the input string, the user entered only a fraction.
The else part of the second if statement uses the String.slice method to separate
the fraction into a numerator part and a denominator part. The fraction is then
divided to create a decimal number.
If there is a blank character in the input string, the user entered mixed number.
In that case, the second if statement uses the String.slice method to
separate the mixed number into a whole part and a fraction part. The fraction part
is processed the same as described above. Then the whole part and fraction part are
added together.
|