将浮点数转换为至少一位小数的字符串(javascript)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28389484/
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
Convert float to string with at least one decimal place (javascript)
提问by Micha?
Let me give you an example.
让我给你举个例子。
var a = 2.0;
var stringA = "" + a;
I will get: stringA = "2"
, but I want: stringA = "2.0"
.
我会得到:stringA = "2"
,但我想要:stringA = "2.0"
。
I don't want to lose precision however, so if:
然而,我不想失去精度,所以如果:
var b = 2.412;
var stringB = "" + b;
I want to get the standard: stringB = "2.412"
.
我想获得标准:stringB = "2.412"
.
That's why toFixed()
won't work here. Is there any other way to do it, than to explicitly check for whole numbers like this?:
这就是为什么toFixed()
在这里不起作用。除了像这样明确检查整数之外,还有其他方法可以做到吗?:
if (a % 1 === 0)
return "" + a + ".0";
else
return "" + a;
采纳答案by jdphenix
If you want to append .0
to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.
如果您想附加.0
到从数字到字符串转换的输出并保持非整数的精度,只需测试一个整数并对其进行特殊处理。
function toNumberString(num) {
if (Number.isInteger(num)) {
return num + ".0"
} else {
return num.toString();
}
}
Input Output
3 "3.0"
3.4567 "3.4567"
回答by Niet the Dark Absol
There is a built-in function for this.
为此有一个内置函数。
var a = 2;
var b = a.toFixed(1);
This rounds the number to one decimal place, and displays it with that one decimal place, even if it's zero.
这会将数字四舍五入到一位小数,并显示一位小数,即使它为零。
回答by Asheliahut
If a is your float do
如果 a 是你的浮动做
var a = 2.0;
var b = (a % 1 == 0) ? a + ".0" : a.toString();
Edited: add reference and change to allow for .0 http://www.w3schools.com/jsref/jsref_tostring_number.asp
编辑:添加引用和更改以允许 .0 http://www.w3schools.com/jsref/jsref_tostring_number.asp
回答by Micha?
For other people looking at this question, it just occurred to me, that to convert a float to a string with at least n
decimal places, one could write:
对于看这个问题的其他人,我突然想到,要将浮点数转换为至少具有n
小数位的字符串,可以这样写:
function toAtLeastNDecimalPlaces(num, n) {
normal_conv = num.toString();
fixed_conv = num.toFixed(n);
return (fixed_conv.length > normal_conv.length ? fixed_conv : normal_conv);
}
Note that according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed, toFixed()
will work for at most 20 decimal places. Therefore the function above will not work for n > 20
.
请注意,根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed,toFixed()
最多可用于小数点后 20 位。因此,上述功能不适用于n > 20
.
Also, the function above does not have any special treatment for scientific notation (But neither do any other answers in this thread).
此外,上面的函数对科学记数法没有任何特殊处理(但该线程中的任何其他答案也没有)。