Possible Duplicate:
Is JavaScript’s Math broken?
I’m running a few very basic functions in javascript to try and convert a float to a currency. For example:
var t = Array(15.90, 15.95, 15.95);
var x = t[0];
if(x%1 == 0)
output += ".0";
if(x%.1 == 0)
output += "0";
Output should yield 0, but for some reason, in some cases, this won’t work and when I echo the value of x to the console, I’ll either get 15.89999999999 or 15.900000000001. Why?
Thanks for your help.
You could just
toFixed()to print out the number of decimals you want:That will always give you a number formatted to two decimal places.
I know that lots of people here will tell you not to use floating point for currency-based computations. However, I find that the precision of floating point numbers is more than sufficient for reasonable dollar amounts. You won’t loose pennies unless you multiply large amounts by small percentages. eg:
1000000 * .0000001 = .099999999