How do you round to 1 decimal place in Javascript?

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

    Try with this:

    var original=28.453
    
    // 1.- round "original" to two decimals
    var result = Math.round (original * 100) / 100  //returns 28.45
    
    // 2.- round "original" to 1 decimal
    var result = Math.round (original * 10) / 10  //returns 28.5
    
    // 3.- round 8.111111 to 3 decimals
    var result = Math.round (8.111111 * 1000) / 1000  //returns 8.111
    

    less complicated and easier to implement...

    with this, you can create a function to do:

    function RoundAndFix (n, d) {
        var m = Math.pow (10, d);
        return Math.round (n * m) / m;
    }
    

    function RoundAndFix (n, d) {
        var m = Math.pow (10, d);
        return Math.round (n * m) / m;
    }
    console.log (RoundAndFix(8.111111, 3));

    EDIT: see this How to round using ROUND HALF UP. Rounding mode that most of us were taught in grade school

提交回复
热议问题