2

Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?

In Javascript, how do I compute the result of 23668-23671.88 to -3.88 instead of -3.8800000000010186 ?

I don't want any rounding, since if I use a windows calc, the result is -3.88.

Is it possible?

Community
  • 1
  • 1
user192344
  • 1,274
  • 6
  • 22
  • 36

2 Answers2

3

If you don't want to round, then you need some way of determining the precision of the variables in your expression and apply that precision to the result of the expression. Unfortunately, JavaScript does not have a way to determine the precision of floats.

However, there is a simple 'hacky' way you can accomplish this:

http://jsfiddle.net/SjxCY/2/

var num = 2.383;
var precision = (num+'').split('.')[1].length;
var final = (234234-num).toFixed(precision);
alert(final);

It's not pretty, but it works.

Elliot B.
  • 17,060
  • 10
  • 80
  • 101
  • I wouldn't rely on `2.383+""` being `"2.383"` – John Dvorak Jan 29 '13 at 09:10
  • I'm not saying it's not always a string. I'm saying it might be longer than expected. – John Dvorak Jan 29 '13 at 09:11
  • I've tested cross-browser. Do you have any examples? – Elliot B. Jan 29 '13 at 09:12
  • What about performing operations other than addition/substraction? (num * 0,5).toFixed(precision) will cut off the last number. – MCL Jan 29 '13 at 09:19
  • The same basic concept applies for addition, subtraction and multiplication--but with caveats. If you subtract 3.333 by 2.222, you have three decimal places of precision in the result--but if you multiply 3.333 by 2.222 you have six decimal places of precision in the final answer. You can use the same little hack to calculate precision, but you may need to total it in a different way depending on the mathematical operator in the expression. – Elliot B. Jan 29 '13 at 09:26
2

If you don't want a rounding kludge, you cannot use floating point numbers and have to find a decimal arithmetic library. Nothing built-in, I am afraid.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656