简体   繁体   English

.toFixed不是.0 *

[英].toFixed not for .0*

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 

LIVE 生活

I want maximum size after dot - 2, but only if numbers after for != 0. So i would like receive: 我希望dot-2之后的最大尺寸,但只有在!之后的数字为0. = 0.所以我希望收到:

1
1.1
1.12
1.12 

How can i make it? 我该怎么做?

.toFixed(x) returns a string. .toFixed(x)返回一个字符串。 Just parse it as a float again: 只需将其解析为浮动:

return parseFloat(val.toFixed(2));

http://jsfiddle.net/mblase75/y5nEu/1/ http://jsfiddle.net/mblase75/y5nEu/1/

Assuming you want String outputs 假设你想要String输出

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"

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

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

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