我是否错过了一个标准API调用,该调用从一个数字中移除尾随的不重要的零?

var x = 1.234000; // to become 1.234
var y = 1.234001; // stays 1.234001

Number.toFixed()和Number.toPrecision()不是我想要的。


当前回答

如果将它转换为字符串,它将不会显示任何尾随零,因为它是作为数字而不是字符串创建的,所以后面的零就不会存储在变量中。

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

其他回答

如果将它转换为字符串,它将不会显示任何尾随零,因为它是作为数字而不是字符串创建的,所以后面的零就不会存储在变量中。

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

我有一个类似的实例,我想在必要的地方使用. tofixed(),但我不想在它不是时使用填充。所以我最终将parseFloat与toFixed结合使用。

固定无填充

parseFloat(n.toFixed(4));

另一个选项几乎做同样的事情 这个答案可能会帮助你做决定

Number(n.toFixed(4));

toFixed将数字四舍五入/填充为特定的长度,但也将其转换为字符串。将其转换回数字类型不仅可以使数字在算术上更安全地使用,还可以自动删除后面的任何0。例如:

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

因为即使你定义了一个后面带0的数字,它们也会被省略。

var n = 1.23000;
 // n == 1.23;

你可以试试这个来缩小浮点数

var n = 0.0000;
n = parseFloat(n.toString()); 

//output n = 0; 
// n = 3.14000; --> n = 3.14;

我是这样做的:

parseFloat(number.toString());

这也是一个很好的解决TypeScript bug的方法。在某些情况下将数字更改为字符串的错误。

我的解决方案如下:

export const floatToStr = (f, ndigit = 2) => {
    const str = f.toFixed(ndigit)
    return ndigit
        ? str
            .replace(/0*$/g, '')
            .replace(/\.$/, '')
        : str
}