119

I have no idea how to do this? I'm adding comma numbers, result is of course always a number with way too many digits after the comma. anyone?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Sten Van den Bergh
  • 1,565
  • 2
  • 13
  • 20

10 Answers10

181

EDIT 2:

Use the Number object's toFixed method like this:

var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)

It rounds 42.0054321 to 42.01

It rounds 0.005 to 0.01

It rounds -0.005 to -0.01 (So the absolute value increases on rounding at .5 border)

jsFiddle example

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • I do mean JavaScript actually. I do not want to remove the comma. Say I have 10.3453564, I want it to be 10.35 – Sten Van den Bergh Nov 04 '10 at 16:15
  • 1
    @Sten - comma or decimal? your question and example disagree. – Nick Craver Nov 04 '10 at 16:16
  • Sorry my english isn't perfect. Let me explain: it is for a bookstore, the numbers I'm working with are prices. So I only want 2 numbers after the comma. (Hopefully I'm saying it right) – Sten Van den Bergh Nov 04 '10 at 16:18
  • 14
    This example does not work if you want to actually round a number, say 0.007 to two decimal places. The result of this is: Math.round(0.007) -> 0.000 and then toFixed(2) -> 0.00. The actual rounding process should render 0.01. – Andrei Dec 10 '13 at 17:13
  • 13
    downvote: answer is incorrect as Math.round() rounds the number, thereby removing all decimals. All toFixed(2) then does is add two trailing zeroes. Just number.toFixed(2) will do. – HammerNL Mar 14 '14 at 08:28
  • 2
    Something should be done as this answer is wrong and other people might not read the comments before blindly using the accepted answer. – Pedro Moreira Apr 21 '15 at 14:17
  • 1
    −1: `3.1415` becomes `3.00` in your example. –  Aug 02 '15 at 10:04
125

UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.

  • toFixed() - method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.
  • Math.round(n) - rounds a number to the nearest integer. Thus turning:

0.5 -> 1; 0.05 -> 0

so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):

  • 0.55555 * 100 = 55.555
  • Math.Round(55.555) -> 56.000
  • 56.000 / 100 = 0.56000
  • (0.56000).toFixed(2) -> 0.56

and this is the code:

(Math.round(number * 100)/100).toFixed(2);
Andrei
  • 4,122
  • 3
  • 22
  • 24
  • I use the same method. Works great – Indiana Kernick Jul 08 '15 at 03:51
  • Caused a problems for examples when you already have float with desired digits after coma like > (Math.round(123.12124 * 100)/100).toFixed(4); ===> 123.1200 – Maksim Nesterenko Jul 06 '17 at 20:52
  • 2
    You forgot to change the rounding math, like this: Math.round(123.12124 * 10000)/10000).toFixed(4). This is if you want to round to the 4th decimal place. – Andrei Jul 07 '17 at 20:12
  • Error: toFixed() _does_ round the number so it isn't a truncation. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – MikeB Mar 13 '19 at 16:37
  • Does not pass for 1.005 – Len Joseph Jul 11 '19 at 13:28
  • toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. The method described above will do rounding well, as mathematician would expect. – Andrei Aug 07 '19 at 16:11
  • `.toFixed()` actually rounds the number. I just tested: `0.6666.toFixed(3)` => 0.667 – Victor Gorban Feb 05 '21 at 15:28
65

This worked for me:

var new_number = float.toFixed(2);

Example:

var my_float = 0.6666

my_float.toFixed(3) # => 0.667
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Raivo
  • 679
  • 5
  • 3
  • I **think** the issue with this is that it doesn't "round" the number, so `0.6666.toFixed(3)` becomes `0.666` instead of `0.667`. @Andrei seems to have the right solution for rounding properly. – Joshua Pinter Jul 07 '15 at 22:55
  • 1
    Ha! Nevermind. I just tested it and `toFixed()` works perfectly: `0.6666.toFixed(3) # => 0.667`. I'll add it to your answer. – Joshua Pinter Jul 07 '15 at 22:57
  • 3
    Shortest and best. This should be the accepted answer. –  Aug 02 '15 at 10:07
15

Previous answers forgot to type the output as an Number again. There is several ways to do this, depending on your tastes.

+my_float.toFixed(2)

Number(my_float.toFixed(2))

parseFloat(my_float.toFixed(2))
Romain Vergnory
  • 1,496
  • 15
  • 30
6

This is not really CPU friendly, but :

Math.round(number*100)/100

works as expected.

Ferdi
  • 540
  • 3
  • 12
  • 23
Tu4n3r
  • 441
  • 5
  • 10
4

Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:

function roundToTwoDigitsAfterComma(floatNumber) {
    return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}

Just in case you are interested how this works:

  1. Multiple with 100 and then do round to keep precision of 2 digits after comma
  2. Divide back into 100 and use toFixed(2) to keep 2 digits after comma and throw other unuseful part
  3. Convert it back to float by using parseFloat() function as toFixed(2) returns string instead

Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
1

use the below code.

alert(+(Math.round(number + "e+2")  + "e-2"));
Ferdi
  • 540
  • 3
  • 12
  • 23
Phoenix
  • 1,470
  • 17
  • 23
  • 2
    This answer does essentially the same thing as the other answers to this 7 years old question, but in a very obscure way, exploiting javascript's implicit type conversions. What qualities of this code convinced you to post it here? – u354356007 Oct 06 '17 at 09:41
  • The quality of this answer is that it made me learn something new I didn't know about JS ;-) – Deblaton Jean-Philippe Dec 13 '17 at 16:25
1

I use this:

function round(value, precision) {

 if(precision == 0)
  return Math.round(value);   

 exp = 1;
 for(i=0;i<precision;i++)
  exp *= 10;

 return Math.round(value*exp)/exp;
}
1

All the suggestions above do not seem to be working with all numbers (negative ones included)

  1. 0.075 => 0.08

  2. -0.075 => -0.08

  3. 0.005 => 0.01

  4. -0.005 => -0.01

    Math.sign(num) * (Math.round((Math.abs(num) + Number.EPSILON) * 1e2) / 1e2);

Rob Bailey
  • 920
  • 1
  • 8
  • 23
SGOmS
  • 11
  • 1
1
console.log((Math.random().toFixed(2)));

I'am use tofixd() still working ok

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 31 '22 at 22:18