Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Addition creates weird decimal issue [duplicate]

Possible Duplicate:
Elegant workaround for JavaScript floating point number problem

Why is it that when adding 2 numbers together using javascript, it will return a crazy number of decimal points?

If I add 285.72 + 142.86 on paper it equals 428.58, you get that same answer with a calculator.

However if I add that number from 2 textboxes it returns 428.58000000000004

Example

I need my javascript to return 428.58. I know I can use .toFixed(), but I'd prefer not to since I don't get why adding two numbers together would create such a crazy number of places after a decimal point.

like image 803
Mark Avatar asked Aug 23 '11 16:08

Mark


People also ask

Why does adding two decimals in JavaScript produce a wrong result?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

Why does JavaScript have rounding errors?

This post doesn't get into the details of floating-point arithmetic, but the short of it is most programming languages use a binary floating-point representation which can only approximate many decimal fractions. This results in rounding errors for the most common approaches to rounding in JavaScript.

How do you control decimals in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.

How do I force two decimal places in JavaScript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.


1 Answers

Not all numbers can be repesented exactly in floating point. Approximations are made and when you have operation after operation on an unexact number the situation gets worse.

See this Wikipedia entry for an example: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

If you changed your addition inputs to something that can be represented exactly by floating point (like 1/8), it would work. Try the numbers: 285.125 and 142.125.

Microsoft .NET has a similar behaviour:

float x = 285.72f

float y = 142.86f

float z = x + y

Results in: z = 428.580017

like image 132
Kevin Kalitowski Avatar answered Sep 26 '22 18:09

Kevin Kalitowski