-2

I'm doing Math.pow(6.9, 3) and getting 328.50900000000007 instead of 328.509. How can I get just 328.509?

I am referring specifically to JavaScript.

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • This is an artefact of how numbers are internally represented by Javascript, for converting you can use `toFixed` - so `Math.pow(6.9, 3).toFixed(3)`. – somethinghere Feb 19 '16 at 15:24
  • This is just a rounding error, 328.50900000000007 is the closest floating-point number to 328.509 Fore more information, see [this other question](https://stackoverflow.com/questions/588004/is-floating-point-math-broken?rq=1) and [What every computer scientist should know about floating point arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html) – Cimbali Feb 19 '16 at 16:13
  • 328.509 cannot possibly be stored in a floating point number. This does not limit to JS, same goes to how 1/3 cannot be stored exactly in decimal. – Derek 朕會功夫 Feb 19 '16 at 16:26

1 Answers1

1

Look here: Number.prototype.toFixed()

So you need to Math.pow(6.9, 3).toFixed(3)

MysterX
  • 2,318
  • 1
  • 12
  • 11
  • 1
    Maybe you should explain that this returns a string representation of the number rounded off to 3 decimals, and not another number? – Cimbali Feb 19 '16 at 16:17