Javascript:将四舍五入的数字格式化为 N 位小数 [英] Javascript: formatting a rounded number to N decimals

查看:24
本文介绍了Javascript:将四舍五入的数字格式化为 N 位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,将数字四舍五入到 N 位小数的典型方法如下:

in JavaScript, the typical way to round a number to N decimal places is something like:

function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

function roundNumber(num, dec) {
  return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}

console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));

然而,这种方法将舍入到 最大 N 个小数位,而我想总是舍入到 N 个小数位.例如,2.0"将四舍五入为2".

However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".

有什么想法吗?

推荐答案

这不是四舍五入的问题,而是显示问题.数字不包含有关有效数字的信息;值 2 与 2.0000000000000 相同.当您将四舍五入的值转换为字符串时,您才能使其显示一定数量的数字.

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

您可以在数字后添加零,例如:

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(注意这里假设客户端的区域设置使用句点作为小数点分隔符,代码需要更多的工作才能用于其他设置.)

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

这篇关于Javascript:将四舍五入的数字格式化为 N 位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆