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

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

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


当前回答

像这样乘以1怎么样?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001

其他回答

当Django在文本字段中显示十进制类型的值时,我也需要解决这个问题。例如,当'1'是值时。它会显示“1.00000000”。如果'1.23'是值,它将显示'1.23000000'(在'decimal_places'设置为8的情况下)

使用parseFloat对我来说不是一个选项,因为它可能不会返回完全相同的值。toFixed不是一个选项,因为我不想四舍五入任何东西,所以我创建了一个函数:

function removeTrailingZeros(value) {
    value = value.toString();

    # if not containing a dot, we do not need to do anything
    if (value.indexOf('.') === -1) {
        return value;
    }

    # as long as the last character is a 0 or a dot, remove it
    while((value.slice(-1) === '0' || value.slice(-1) === '.') && value.indexOf('.') !== -1) {
        value = value.substr(0, value.length - 1);
    }
    return value;
}

对于非常小的数,这些解都不适用。http://numeraljs.com/为我解决了这个问题。

parseFloat(0.00000001.toFixed(8));
// 1e-8

numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"

使用parseFloat()实现了这个目的。我不明白为什么这些复杂的解。

所以你想

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

没有附加条件,只需尝试Number()。

Var x = 1.234000, //变成1.234 Y = 1.234001, //保持1.234001 x_ =数字(x), y_ =数字(y); y_ console.log(间);

如果还想处理数字错误,可以使用Intl。NumberFormat或Number.toLocaleString()

new Intl.NumberFormat().format(0.0100) // "0.01"
new Intl.NumberFormat().format(0.010000000000001) // "0.01"
new Intl.NumberFormat().format(0.009999999999999) // "0.01"
console.log((0.0100).toLocaleString()) // "0.01"
console.log((0.010000000000001).toLocaleString()) // "0.01"
console.log((0.009999999999999).toLocaleString()) // "0.01"