3

I have this

Math.round((Math.abs(21600 / 3600))*100)/100
>> 6 # want 6.00
Math.round((Math.abs(21000 / 3600))*100)/100
>> 5.83 # This is right

I need 2 decimals on whole number.

Andreas Lyngstad
  • 4,887
  • 2
  • 36
  • 69

4 Answers4

7

You can use .toFixed(), but there's no need to manually round the value to the nearest 0.01 first - the .toFixed function will do that for you.

var str = Math.abs(21600 / 3600).toFixed(2);
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • all votes gratefully accepted - I'm trying to hit 100k rep today ;-) – Alnitak Apr 30 '13 at 11:05
  • 1
    toFixed() won't result in a number, but rather a string – Confused May 26 '16 at 13:44
  • @Confused indeed, and that's why my variable is named `str`. Rounding floating point numbers is invariably a _presentation_ problem, not a math one. – Alnitak May 26 '16 at 13:46
  • I've been struggling with this exact topic all day. Maybe it's just my ocd but I can't stand that it's so hard to maintain a #.0 in js! – Confused May 26 '16 at 13:48
2

Use Number.prototype.toFixed()MDN.

(Math.round((Math.abs(21600 / 3600))*100)/100).toFixed( 2 );
jAndy
  • 231,737
  • 57
  • 305
  • 359
1

Try this:

(Math.round((Math.abs(21600 / 3600))*100)/100).toFixed(2)
robertklep
  • 198,204
  • 35
  • 394
  • 381
1

You can use toFixed() method:

var num = num.toFixed(6);

Now num wil be equal to 6.00

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161