Fractions and Foating-Points

Floating-point arithmetic on a computer is hazardous, at best. This post is not a detail description of the problem. Varied descriptions of the problem already abound, like this one, for example. There’s also documented pain out there to understand that it’s not just your computer 🙂 No, this post is just one way of getting around the problem in a particular context.

The environment: JavaScript. The problem: convert decimals to fractions and fractions to decimals. Getting a decimal is straightforward:

function fractiontodecimal( wholenumber, numerator, denominator ) {
wholenumber = parseFloat(wholenumber);
numerator = parseFloat(numerator);
denominator = parseFloat(denominator);
return ( ( ( wholenumber * denominator ) + numerator) / denominator );
}

Obtaining a fraction was slightly more insane since in JavaScript
23.8 * 10 = 238
but
23.88 * 10 = 238.79999999999998

Not exactly what you need to work with. As you can imagine, inside a loop of sorts, and if the number becomes very small and you divide by it, you start getting bigger errors. Anyways, that’s a digression in itself. What i needed was a reliable way to multiple by a float by an integer, 10, and get a predictable response. In other words, i just needed to keep shifting the decimal point. Most immediate response might be: string manipulation. Isn’t that what JavaScript is for? :p

Another way was using e-notation. 23.88 being represented as 23.88e0. Multiply by 10: 23.88e1, and so on. The good news is you still get to do a little string manipulation, but not nearly as hectic as finding and moving a “.”

The particularly heavy looking string manipulation looking like:

newDecimal = mantissa + “e” + exponent;
That wasn’t so hard, now was it? 😀

Browse through the code for decimal.htm (HTLM page with JavaScript)