Rounding numbers to 2 digits after comma

前端 未结 8 1190
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 12:14

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?

相关标签:
8条回答
  • 2020-11-28 12:55

    This worked for me:

    var new_number = float.toFixed(2);
    

    Example:

    var my_float = 0.6666
    
    my_float.toFixed(3) # => 0.667
    
    0 讨论(0)
  • 2020-11-28 12:58

    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(roudedString); // 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

    0 讨论(0)
  • 2020-11-28 13:01

    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))
    
    0 讨论(0)
  • 2020-11-28 13:02

    This is not really CPU friendly, but :

    Math.round(number*100)/100
    

    works as expected.

    0 讨论(0)
  • 2020-11-28 13:03

    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);
    
    0 讨论(0)
  • 2020-11-28 13:03

    use the below code.

    alert(+(Math.round(number + "e+2")  + "e-2"));
    
    0 讨论(0)
提交回复
热议问题