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

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

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


当前回答

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

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

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

其他回答

如果由于任何原因(比如涉及到金钱浮动)不能使用float,并且已经从表示正确数字的字符串开始,您可以发现这个解决方案很方便。它将表示数字的字符串转换为表示数字的字符串,后面不带零。

function removeTrailingZeroes( strAmount ) {
    // remove all trailing zeroes in the decimal part
    var strDecSepCd = '.'; // decimal separator
    var iDSPosition = strAmount.indexOf( strDecSepCd ); // decimal separator positions
    if ( iDSPosition !== -1 ) {
        var strDecPart = strAmount.substr( iDSPosition ); // including the decimal separator

        var i = strDecPart.length - 1;
        for ( ; i >= 0 ; i-- ) {
            if ( strDecPart.charAt(i) !== '0') {
                break;
            }
        }

        if ( i=== 0 ) {
            return strAmount.substring(0, iDSPosition);
        } else {
            // return INTPART and DS + DECPART including the rightmost significant number
            return strAmount.substring(0, iDSPosition) + strDecPart.substring(0,i + 1);
        }
    }

    return strAmount;
}

当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;
}

所以你想

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(间);

我的解决方案如下:

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

我有一个类似的实例,我想在必要的地方使用. 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;