简体   繁体   English

Javascript:将舍入的数字格式化为N个小数

[英]Javascript: formatting a rounded number to N decimals

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 maximum of N decimal places while I want to always round to N decimal places. 但是,这种方法将最大舍入到N个小数位,而我想始终舍入到N个小数位。 For example "2.0" would be rounded to "2". 例如,“ 2.0”将四舍五入为“ 2”。

Any ideas? 有任何想法吗?

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... 等等...

I found a way. 我找到了一个方法。 This is Christoph's code with a fix: 这是克里斯托夫的代码,带有修复程序:

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 here if you are curious as to why I added the "+ 1". 如果您对为什么我添加“ +1”感到好奇,请在此处阅读使用数组构造函数重复字符的详细信息。

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. 值2与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.) (请注意,这是假定客户端的区域设置使用句点作为小数点分隔符,该代码需要更多工作才能用于其他设置。)

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

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. 下面的代码可用于将您自己的Math.round版本添加到具有精度参数的名称空间中。 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. 与上面的示例中的十进制舍入不同,它不执行字符串转换,也不执行字符串转换,而precision参数的工作方式与PHP和Excel相同,其中正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

from Mozilla Developer reference for Math.round() 来自Mozilla开发人员的Math.round()参考

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;
}

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 . 过去,当我编写数据处理E-Slate组件时,不得不在Java上使用这种逻辑。 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). 那是因为我发现将0多次加0.1会得到一些意想不到的长小数部分(这是由于浮点运算)。

A user comment at Format number to always show 2 decimal places calls this technique scaling. 用户在格式编号处始终显示2个小数位的注释称为此技术缩放。

Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead: 有人提到有些情况无法按预期进行,在http://www.jacklmoore.com/notes/rounding-in-javascript/中建议使用以下方法:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

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. 在perl中,对sprintf()的调用是一种舍入方法,但是javascript本身没有该功能。

http://perldoc.perl.org/functions/sprintf.html http://perldoc.perl.org/functions/sprintf.html

Does that help? 有帮助吗?

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); 用法: roundOff(600.23458,2); will return 600.23 将返回600.23

If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. 如果您不太在意舍入,只需添加toFixed(x),然后删除尾随的0es和点(如果需要)。 It is not a fast solution. 这不是一个快速的解决方案。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM