如何在 JavaScript 中舍入一个数字?.toFixed() 返回一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2283566/
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
How can I round a number in JavaScript? .toFixed() returns a string?
提问by Derek Adair
Am I missing something here?
我在这里错过了什么吗?
var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string
Whydoes .toFixed()return a string?
为什么会.toFixed()返回一个字符串?
I want to round the number to 2 decimal digits.
我想将数字四舍五入为 2 个十进制数字。
采纳答案by Chris Jester-Young
It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.
它返回一个字符串,因为 0.1 及其幂(用于显示小数)在二进制浮点系统中无法表示(至少不是完全准确)。
For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimalfor proving my point. :-P)
例如,0.1 真的是 0.1000000000000000055511151231257827021181583404541015625,而 0.01 真的是 0.010000000000000006737370000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000之间分别为0.1和0.1 (感谢您BigDecimal证明了我的观点。:-P)
Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.
因此(没有十进制浮点数或有理数类型),将其作为字符串输出是将其精确调整到显示所需精度的唯一方法。
回答by m93a
Number.prototype.toFixedis a function designed to formata numberbefore printing it out. It's?from the family of toString, toExponentialand toPrecision.
Number.prototype.toFixed是一种用于在打印之前格式化数字的函数。它来自toString,toExponential和的家庭toPrecision。
To round a number, you would do this:
要舍入一个数字,您可以这样做:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
.
.
Or if you want a “native-like” function, you can extend the prototype:
或者,如果你想要一个“类似原生”的函数,你可以扩展原型:
Number.prototype.toFixedNumber = function(digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;
//or even hexadecimal
someNumber = 0xAF309/256 //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";
However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.
但是,请记住,在编写模块时污染原型被认为是不好的,因为模块不应该有任何副作用。因此,对于模块,请使用第一个函数。
回答by Eve juan
I've solved this problem by changing this:
我通过改变这个解决了这个问题:
someNumber = someNumber.toFixed(2)
...to this:
...到这个:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
但是,这会将数字转换为字符串并再次解析它,这将对性能产生重大影响。如果您关心性能或类型安全,请查看其他答案。
回答by sirlunchalot
Why not use parseFloat?
为什么不使用parseFloat?
var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number
回答by Nizar
I solved it with converting it back to number using JavaScript's Number()function
我通过使用 JavaScript 的Number()函数将其转换回数字来解决它
var x = 2.2873424;
x = Number(x.toFixed(2));
回答by Joel Coehoorn
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
当然它返回一个字符串。如果您想对数字变量进行舍入,您可以使用 Math.round() 来代替。toFixed 的要点是将数字格式化为固定的小数位以显示给用户。
回答by meisam
You can simply use a '+' to convert the result to a number.
您可以简单地使用“+”将结果转换为数字。
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
回答by Tomas Vana
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00etc. so it has to be a string.
当它应该格式化一个数字时,你希望它返回什么?如果你有一个数字,你几乎不能用它做任何事情,因为例如2 == 2.0 == 2.00等等,所以它必须是一个字符串。
回答by Pyro
To supply an example of why it has to be a string:
提供一个为什么它必须是字符串的例子:
If you format 1.toFixed(2) you would get '1.00'.
如果你格式化 1.toFixed(2) 你会得到“1.00”。
This is not the same as 1, as 1 does not have 2 decimals.
这与 1 不同,因为 1 没有 2 位小数。
I know JavaScript isn't exactly a performancelanguage, but chances are you'd get better performance for a rounding if you use something like: roundedValue = Math.round(value * 100) * 0.01
我知道 JavaScript 并不完全是一种性能语言,但是如果您使用以下内容,您可能会获得更好的舍入性能: roundedValue = Math.round(value * 100) * 0.01
回答by Christoph
Because its primary use is displaying numbers? If you want to round numbers, use Math.round()with apropriate factors.
因为它的主要用途是显示数字?如果您想对数字进行四舍五入,请使用Math.round()适当的因子。

