1

This may be a noob question to ask. It is about Math.pow in JavaScript.

var amount = 0.55;
var decimal = 18;
var value = amount * Math.pow(10, decimal);

console.log('amount: ' + amount + ' value: ' + value);

If the amount is 0.55,I expected the returned value to be 550000000000000000.

But, instead it returns 550000000000000060

If the amount is 0.56,I expected the returned value to be 560000000000000000.

But, instead it returns 560000000000000060

How do I get the expected returned value and why does it happen?

JayB Kim
  • 327
  • 5
  • 16
  • What's `decimal` in your code? You haven't defined it. – T.J. Crowder Apr 05 '18 at 07:38
  • @T.J.Crowder Oh,,,my bad I will edit it now. – JayB Kim Apr 05 '18 at 07:39
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER – CBroe Apr 05 '18 at 07:40
  • @T.J Crowder I see why it is happnening now. It is because JavaScript treats decimals as floating point numbers, it is subjecting to rounding error. Thank you! – JayB Kim Apr 05 '18 at 07:58
  • @CBroe Thank you for the reference. – JayB Kim Apr 05 '18 at 07:58
  • @JayBKim: Yes, specifically IEEE-754 double-precision binary floating point, which is very fast, but imprecise. (Someday maybe JavaScript will have the new [2008] IEEE-754 double-precision *decimal* floating point, like [decimal64](https://en.wikipedia.org/wiki/Decimal64_floating-point_format) or decimal128...) – T.J. Crowder Apr 05 '18 at 08:04

0 Answers0