PDA

View Full Version : Currency Formatting adding junk decimals



suresh_nagar
6 May 2014, 2:53 PM
The currency format if done for more than 6 decimal places is adding junk decimals in the end.
e.g.
try this
var number = 8888888888.67;
console.log(parseFloat(number));
console.log(Ext.util.Format.currency(parseFloat(number), "",10));


this gives the output as - $8,888,888,888.6700000763

let me know how can i format the numbers till 10 decimal digit precision without modifying the contents of the number.

Scott Mildenberger
8 May 2014, 2:02 PM
Maybe try number.toFixed(2) instead of parseFloat. Floating point numbers are approximations.

skirtle
8 May 2014, 4:53 PM
Simplifying the test case a little:


Ext.util.Format.currency(8888888888.67, "", 10); // => $8,888,888,888.6700000763

To be clear, this works fine:


Ext.util.Format.currency(8888888888.67);

The problem is that you're asking for 10 decimal places and JavaScript numbers just aren't precise to that level of precision. For which currency does this make sense?

You get the same if you do this:


(8888888888.67).toFixed(10)

More generally, this does give some indication as to why representing money as a floating point number is a bad idea.

Personally, I find this example entertaining:


0.1 + 0.2 == 0.3; // => false

Yeah, scary.