开发者

javascript Addition creates weird decimal issue [duplicate]

This question already has answers here: Closed 11 years ago.

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.5开发者_运维技巧8000000000004

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.


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


You have to use .toFixed because Javascript uses IEEE 754-2008 floating point arithmetics which cause this behavior. These binary floating point numbers are just approximate so you have to use rounding.


This is because floats do not use an exact representation of some decimal numbers, therefore arithmetic imprecision can arise. I do not know of any better approach besides rounding the number to whatever precision you require, like toFixed does

http://www.mredkj.com/javascript/nfbasic2.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜