Wednesday 5 April 2017

javascript - Math.round() round numbers up not 2 decimals after comma




Here is my code:



Math.round((7/2)).toFixed(2)


this code print: "4.00" while it should print 3.50. Where is a problem? How I can round this value whithout rounding-up?


Answer



No, it should print "4.00", and that's why it is: You've rounded the 3.5 to 4, then called toFixed(2) on 4.




If you want "3.50", then don't round it to a whole number first; toFixed will do rounding to the number of places you ask for (although rounding isn't required at all for 7/2 if you're outputting to two decimal places):



(7/2).toFixed(2)


E.g.:





snippet.log((7/2).toFixed(2));








Example where toFixed actually does rounding:






snippet.log((1.237).toFixed(2)); // "1.24"






No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...