How do you round to 1 decimal place in Javascript?

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

    If you use Math.round(5.01) you will get 5 instead of 5.0.

    If you use toFixed you run into rounding issues.

    If you want the best of both worlds combine the two:

    (Math.round(5.01 * 10) / 10).toFixed(1)
    

    You might want to create a function for this:

    function roundedToFixed(_float, _digits){
      var rounded = Math.pow(10, _digits);
      return (Math.round(_float * rounded) / rounded).toFixed(_digits);
    }
    

提交回复
热议问题