开发者

Javascript issue with math calculations

Why is i开发者_如何学Got if I do this in javascript, I get the following result:

1234.56 * 10 = 12345.599999999999

It should be 123456. How can I get around this problem?

Thanks.


Floating points are not exact, since there are ifinite numbers at their range [or in any range to be more exact], and only a finite number of bits to store this data.

Have a look at what every programmer should know about floating point arithmetics.


Another easy solution:

parseFloat((1234.56 * 10).toPrecision(12))

and the result will be: 12345.6, and YES... it works with decimal numbers.


As the others said, floating points and so on.

Easy solution would be to do something like this:

var answer = parseInt(1234.56 * 10);

Or just use Math.round?


All numbers in JS are internally defined by float and drop the less significant digits if needed.

(10000000000000000000000000000 + 1) == 10000000000000000000000000000
// this will return true

And javascript is well known for droping bits quite often in numbers. So handle with care

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜