How do you round to 1 decimal place in Javascript?

前端 未结 21 1439
难免孤独
难免孤独 2020-11-22 08:49

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?

I tried the *10, round, /10 but it leaves two decimals at the end of

相关标签:
21条回答
  • 2020-11-22 09:18

    I vote for toFixed(), but, for the record, here's another way that uses bit shifting to cast the number to an int. So, it always rounds towards zero (down for positive numbers, up for negatives).

    var rounded = ((num * 10) << 0) * 0.1;
    

    But hey, since there are no function calls, it's wicked fast. :)

    And here's one that uses string matching:

    var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
    

    I don't recommend using the string variant, just sayin.

    0 讨论(0)
  • 2020-11-22 09:18

    To complete the Best Answer:

    var round = function ( number, precision )
    {
        precision = precision || 0;
        return parseFloat( parseFloat( number ).toFixed( precision ) );
    }
    

    The input parameter number may "not" always be a number, in this case .toFixed does not exist.

    0 讨论(0)
  • 2020-11-22 09:18
    Math.round( mul/count * 10 ) / 10
    
    Math.round(Math.sqrt(sqD/y) * 10 ) / 10
    

    Thanks

    0 讨论(0)
提交回复
热议问题