How do you round to 1 decimal place in Javascript?

前端 未结 21 1928
难免孤独
难免孤独 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 08:54

    This seems to work reliably across anything I throw at it:

    function round(val, multiplesOf) {
      var s = 1 / multiplesOf;
      var res = Math.ceil(val*s)/s;
      res = res < val ? res + multiplesOf: res;
      var afterZero = multiplesOf.toString().split(".")[1];
      return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
    }
    

    It rounds up, so you may need to modify it according to use case. This should work:

    console.log(round(10.01, 1)); //outputs 11
    console.log(round(10.01, 0.1)); //outputs 10.1
    

提交回复
热议问题