3

I have a js that grabs values, multiplies, sums, divides, and then puts them in a cell of a table. The result can be up to (I think) 15 decimal places. How do I limit it to two?

ex.: Result of math operation: 5.223567 I want: 5.22

I want to truncate or round the remaining decimal places. I am open to solutions that requires resources outside of js but would prefer a js solution if one exists.

Kynan Pacheco
  • 207
  • 2
  • 3
  • 10

3 Answers3

16

Use .toFixed.

yourNumber.toFixed(2);

Notice that .toFixed will return a string, as JavaScript uses 64 bit floating point numbers which cannot guarantee accuracy. (In layman's terms, JS cannot represent 0.1 accurately so it has to return a string.)

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
6
 (5.223567).toFixed(2)

the method toFixed rounds to a number of decimals.

Bee157
  • 576
  • 6
  • 14
  • 2
    why downvote when the answer is perfectly valid. Even no comment explaining why this is perceived incorrect. – Bee157 Jul 28 '17 at 20:12
  • Trivial questions with easily discoverable dupes are asked a lot in this tag. Users get tired of it, and downvote answers to these questions. There's more info over on [meta], if you search for it. –  Jul 28 '17 at 20:18
  • I understand, will try to add comment to the trivial questions ;) instead of an answer. – Bee157 Jul 28 '17 at 20:27
  • It'll probably save you downvotes in the future. Good luck. –  Jul 28 '17 at 20:29
5

If you do not want to use .toFixed() you could also

Math.round(num * Math.pow(10,x)) / Math.pow(10,x)

where x is the number of decimal places and num is the original number

Mr DOOD
  • 61
  • 1
  • 1