0

When using Math.pow in Javascript, I am getting unexpected result. See my experiments. Used Chrome V: 79.0.3945.130, Console to get these results:

Math.pow(10, -1) Expected: 0.1, Result: 0.1

Math.pow(10, -2) Expected: 00.1, Result: 00.1

Math.pow(10, -3) Expected: 000.1, Result: 000.1

Math.pow(10, -4) Expected: 0000.1, Result: 0.00009999999999999999

Math.pow(10, -5) Expected: 00000.1, Result: 0.000009999999999999999

Math.pow(10, -6) Expected: 000000.1, Result: 000000.1

enter image description here

The case of -4 and -5 is making this unusable for me for the reason I wanted to use it. (offsetting numbers with a set decimal length for display)

Any way to ensure the "expected" behavior?

DDan
  • 8,068
  • 5
  • 33
  • 52

1 Answers1

1

Use it like this

Math.pow(10,-4).toFixed(4)
Math.pow(10,-5).toFixed(5)

console.log(Math.pow(10, -2).toFixed(2))
console.log(Math.pow(10, -3).toFixed(3))
console.log(Math.pow(10, -4).toFixed(4))
console.log(Math.pow(10, -5).toFixed(5))
console.log(Math.pow(10, -6).toFixed(6))

let number = -7
console.log(Math.pow(10, number).toFixed(Math.abs(number)))
Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35