How do you round to 1 decimal place in Javascript?

前端 未结 21 1785
难免孤独
难免孤独 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:09

    I made one that returns number type and also places decimals only if are needed (no 0 padding).

    Examples:

    roundWithMaxPrecision(11.234, 2); //11.23
    roundWithMaxPrecision(11.234, 1); //11.2
    roundWithMaxPrecision(11.234, 4); //11.23
    roundWithMaxPrecision(11.234, -1); //10
    
    roundWithMaxPrecision(4.2, 2); //4.2
    roundWithMaxPrecision(4.88, 1); //4.9
    

    The code:

    function roundWithMaxPrecision (n, precision) {
        let precisionWithPow10 = Math.pow(10, precision);
        return Math.round(n * precisionWithPow10) / precisionWithPow10;
    }
    

提交回复
热议问题