javascript .toFixed 不适用于 .0*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17555999/
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
.toFixed not for .0*
提问by user2565589
I have a few values:
我有几个价值观:
var one = 1.0000
var two = 1.1000
var three = 1.1200
var four = 1.1230
and function:
和功能:
function tofixed(val)
{
return val.toFixed(2);
}
this return:
这个回报:
1.00
1.10
1.12
1.12
I want maximum size after dot - 2, but only if numbers after for != 0. So i would like receive:
我想要点之后的最大尺寸 - 2,但前提是数字之后为 != 0。所以我想收到:
1
1.1
1.12
1.12
How can i make it?
我怎样才能做到?
回答by Blazemonger
.toFixed(x)
returns a string. Just parse it as a float again:
.toFixed(x)
返回一个字符串。只需再次将其解析为浮点数:
return parseFloat(val.toFixed(2));
回答by Paul S.
Assuming you want Stringoutputs
假设你想要字符串输出
function myFixed(x, d) {
if (!d) return x.toFixed(d); // don't go wrong if no decimal
return x.toFixed(d).replace(/\.?0+$/, '');
}
myFixed(1.0000, 2); // "1"
myFixed(1.1000, 2); // "1.1"
myFixed(1.1200, 2); // "1.12"
myFixed(1.1230, 2); // "1.12"
回答by Niet the Dark Absol
The "correct" way to do it is as follows:
“正确”的方法如下:
return Math.round(num*100)/100;
If you want to truncate it to two decimal places (ie. 1.238 goes to 1.23 instead of 1.24), use floor
instead of round
.
如果要将其截断为两位小数(即 1.238 变为 1.23 而不是 1.24),请使用floor
代替round
。