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.

0

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Nice explanation of why toFixed returns a string.
He didn't say he wanted a string though.
6
 (5.223567).toFixed(2) 

the method toFixed rounds to a number of decimals.

4 Comments

why downvote when the answer is perfectly valid. Even no comment explaining why this is perceived incorrect.
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 Stack Overflow, if you search for it.
I understand, will try to add comment to the trivial questions ;) instead of an answer.
It'll probably save you downvotes in the future. Good luck.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.