你如何在Javascript中四舍五入到小数点后一位?

新手上路,请多包涵

您可以将javascript中的数字四舍五入到小数点后1个字符(正确四舍五入)吗?

我尝试了 *10, round, /10 但它在 int 的末尾留下了两位小数。

原文由 Walker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 775
2 个回答

Math.round(num * 10) / 10 有效,这里是一个例子……

 var number = 12.3456789
 var rounded = Math.round(number * 10) / 10
 // rounded is 12.3

如果你希望它有一位小数,即使那是 0,然后添加……

 var fixed = rounded.toFixed(1)
 // fixed is always to 1 dp
 // NOTE: .toFixed() returns a string!

 // To convert back to number format
 parseFloat(number.toFixed(2))
 // 12.34
 // but that will not retain any trailing zeros

 // So, just make sure it is the last step before output,
 // and use a number format during calculations!

编辑:添加带有精确功能的圆形…

使用这个原则,作为参考,这里有一个方便的小圆函数,它需要精度……

 function round(value, precision) {
 var multiplier = Math.pow(10, precision || 0);
 return Math.round(value * multiplier) / multiplier;
 }

… 用法 …

 round(12345.6789, 2) // 12345.68
 round(12345.6789, 1) // 12345.7

… 默认舍入到最接近的整数(精度 0)…

 round(12345.6789) // 12346

…并且可用于四舍五入到最接近的 10 或 100 等…

 round(12345.6789, -1) // 12350
 round(12345.6789, -2) // 12300

…并正确处理负数…

 round(-123.45, 1) // -123.4
 round(123.45, 1) // 123.5

…并且可以与 toFixed 结合以一致地格式化为字符串 …

 round(456.7, 2).toFixed(2) // "456.70"

原文由 Billy Moon 发布,翻译遵循 CC BY-SA 4.0 许可协议

var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5

原文由 Pablo Fernandez 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题