如何在javascript中获得1.450 = 1.5? (舍入到小数点后1位)

时间:2012-10-02 11:20:44

标签: javascript

  

可能重复:
  How do you round to 1 decimal place in Javascript?

我的价值是1.450,我必须将它四舍五入到小数点后1位。

我希望Javascript中的1.450 = 1.5可以解决这个问题。

4 个答案:

答案 0 :(得分:11)

你需要这个:

var mynum = 1.450,
  rounded = Math.round(mynum * 10) / 10;

答案 1 :(得分:4)

假设你有

var original=28.453;

然后

var result=Math.round(original*10)/10  //returns 28.5

来自http://www.javascriptkit.com/javatutors/round.shtml

您还可以看到How do you round to 1 decimal place in Javascript?

答案 2 :(得分:2)

鉴于你的fiddle,最简单的改变是:

result = sub.toFixed(1) + "M";

为:

result = Math.ceil(sub.toFixed(1)) + "M";

答案 3 :(得分:2)

如果您使用Math.round,那么1将获得1.01,而不是1.0

如果您使用toFixed,则会遇到rounding issues

如果你想要两个世界中最好的结合两者:

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

您可能想为此创建一个函数:

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