0

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?

Ram
  • 143,282
  • 16
  • 168
  • 197
Newester
  • 1,457
  • 2
  • 14
  • 26
  • _The Math.round() function returns the value of a number rounded to the nearest integer._ [`Math.round()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/round) – Andreas Apr 10 '15 at 16:37
  • So how I can round this value without rounding-up ?? – Newester Apr 10 '15 at 16:38
  • 2
    Why are you rounding at all? `(7/2).toFixed(2)` would yield "3.50". – Blazemonger Apr 10 '15 at 16:38

1 Answers1

4

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));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Example where toFixed actually does rounding:

snippet.log((1.237).toFixed(2)); // "1.24"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875