Javascript和奇怪的数字

时间:2016-07-22 00:40:20

标签: javascript math numbers

我需要增加任何数字,不管小数位数。唯一的自定义函数是decimalPlaces(),如下所示:

function decimalPlaces(num) {
  var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  if (!match) { return 0; }
  return Math.max( 0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0) );
}

那么,那么,例如(在Node中):

a = 2.11
> 2.11
places = decimalPlaces(a)
> 2
additive = Math.pow(10,places*-1);
> 0.01
a + additive
> 2.11999999999999997

适用于90%的案例,但不适用于此案例。我知道有一种方法可以使用指数来进出这个问题(将数字乘以10 ^位并加1),但我只是好奇 - 这个奇怪的浮点问题出现在哪里?要成为一些非常简单的数学?

0 个答案:

没有答案
相关问题