Javascript:将四舍五入的数字格式化为 N 位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2221167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: formatting a rounded number to N decimals
提问by hoju
in JavaScript, the typical way to round a number to N decimal places is something like:
在 JavaScript 中,将数字四舍五入到 N 位小数的典型方法是这样的:
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));
However this approach will round to a maximumof N decimal places while I want to alwaysround to N decimal places. For example "2.0" would be rounded to "2".
然而,这种方法将舍入到最多N 个小数位,而我想总是舍入到 N 个小数位。例如,“2.0”将四舍五入为“2”。
Any ideas?
有任何想法吗?
采纳答案by Guffa
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.
这不是四舍五入的问题,而是显示问题。数字不包含有关有效数字的信息;值 2 与 2.0000000000000 相同。当您将四舍五入的值转换为字符串时,您将使其显示一定数量的数字。
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.)
(请注意,这里假设客户端的区域设置使用句点作为小数点分隔符,代码需要更多工作才能用于其他设置。)
回答by David
I think that there is a more simple approach to all given here, and is the method Number.toFixed()already implemented in JavaScript.
我认为这里给出的所有方法都有更简单的方法,并且该方法Number.toFixed()已经在 JavaScript 中实现。
simply write:
简单地写:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
等等...
回答by Elias Zamaria
I found a way. This is Christoph's code with a fix:
我找到了一个方法。这是 Christoph 的修复代码:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
Read the details of repeating a character using an array constructor hereif you are curious as to why I added the "+ 1".
如果您对我添加“+ 1”的原因感到好奇,请在此处阅读使用数组构造函数重复字符的详细信息。
回答by de.la.ru
There's always a better way for doing things.
总有更好的做事方式。
var number = 51.93999999999761;
I would like to get four digits precision: 51.94
我想获得四位数精度:51.94
just do:
做就是了:
number.toPrecision(4);
the result will be: 51.94
结果将是:51.94
回答by JohnnyBizzle
PHP-Like rounding Method
类似 PHP 的舍入方法
The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.
下面的代码可用于将您自己的 Math.round 版本添加到您自己的命名空间中,该命名空间采用精度参数。与上面示例中的 Decimal 四舍五入不同,它不执行与字符串的转换,并且 precision 参数的工作方式与 PHP 和 Excel 相同,正 1 将四舍五入到小数点后 1 位,-1 将四舍五入到十位。
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
回答by KRISHNA TEJA
I think below function can help
我认为以下功能可以提供帮助
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2);will return 600.23
用法:roundOff(600.23458,2);会回来600.23
回答by George Birbilis
This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):
这适用于四舍五入到 N 位(如果您只想截断到 N 位,请删除 Math.round 调用并使用 Math.trunc 一个):
function roundN(value, digits) {
var tenToN = 10 ** digits;
return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}
Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).
过去我在编写数据操作 E-Slate 组件时不得不在 Java 中诉诸这种逻辑。那是因为我发现将 0.1 多次添加到 0 最终会得到一些出乎意料的长小数部分(这是由于浮点运算)。
A user comment at Format number to always show 2 decimal placescalls this technique scaling.
格式编号始终显示 2 个小数位的用户评论称为此技术缩放。
Some mention there are cases that don't round as expected and at http://www.Hymanlmoore.com/notes/rounding-in-javascript/this is suggested instead:
有人提到有些情况没有按预期四舍五入,在http://www.Hymanlmoore.com/notes/rounding-in-javascript/建议改为:
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
回答by Christoph
Hopefully working code (didn't do much testing):
希望工作代码(没有做太多测试):
function toFixed(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
回答by Paul
Here's a link to a Javascript sprintf,
这是 Javascript sprintf 的链接,
http://www.webtoolkit.info/javascript-sprintf.html
http://www.webtoolkit.info/javascript-sprintf.html
A call to sprintf() is one rounding methodology in perl, but javascript doesn't have that function natively.
对 sprintf() 的调用是 perl 中的一种舍入方法,但 javascript 本身没有该功能。
http://perldoc.perl.org/functions/sprintf.html
http://perldoc.perl.org/functions/sprintf.html
Does that help?
这有帮助吗?
回答by Juan Carrey
If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.
如果您真的不关心舍入,只需添加一个 toFixed(x) ,然后在必要时删除尾随的 0es 和点。这不是一个快速的解决方案。
function format(value, decimals) {
if (value) {
value = value.toFixed(decimals);
} else {
value = "0";
}
if (value.indexOf(".") < 0) { value += "."; }
var dotIdx = value.indexOf(".");
while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
return value;
}

