开发者

How to work around the decimal problem in JavaScript? [duplicate]

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

Possible Duplicates:

Strange problem comp开发者_StackOverflow中文版aring floats in objective-C

Is JavaScript’s math broken?

1.265 * 10000 = 126499.99999999999 ?????

After watching this I discovered that in JavaScript:

0.1 + 0.2 === 0.3

evaluates to false.

Is there a way to work around this?


The best and only answer I have found that provides accurate results is to use a Decimal library. The BigDecimal java class has been ported to javascript, see my answer in this SO post.

Note: Scaling values will "treat" the issue but will not "cure" it.


How about

function isEqual(a, b)
{
  var epsilon = 0.01; // tunable 
  return Math.abs(a - b) < epsilon;
}


This is a problem inherent in binary numbers that hits all major programming languages.

Convert decimal .1 (1/10) to binary by hand - you'll find it has a repeating mantissa and can't be represented exactly. Like trying to represent 1/3 as a decimal.


You should always compare floating point numbers by using a constant (normally called epsilon) to determine much can two numbers differ to be considered "equal".


Use fixed-point math (read: integers) to do math where you care about that kind of precision. Otherwise write a function that compares your numbers within a range that you can accept as being "close enough" to equal.


Just an idea. Multiply 10000 (or some similarly big number as long as its more than your max number of decimals) to all your values before you compare them, that why they will be integers.

function padFloat( val ) {
  return val * 10000;
}

padFloat( 0.1 ) + padFloat( 0.2 ) === padFloat( 0.3 );


You can of course multiply each number like

10 * 0.1 + 10 * 0.2 === 10 * 0.3

which evaluates to true.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜