我是否错过了一个标准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;

其他回答

我的解决方案如下:

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

toFixed方法将在必要时进行适当的舍入。它还将添加尾随零,这并不总是理想的。

(4.55555).toFixed(2);
//-> "4.56"

(4).toFixed(2);
//-> "4.00"

如果将返回值转换为数字,则后面的零将被删除。这是一种比自己进行舍入或截断计算更简单的方法。

+(4.55555).toFixed(2);
//-> 4.56

+(4).toFixed(2);
//-> 4

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

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

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

我有基本相同的需求,但发现没有内置机制来实现此功能。

除了去掉后面的0之外,我还需要为用户的当前语言环境(即123,456.789)对输出进行四舍五入和格式化。

我在这方面的所有工作都包括在GitHub: https://github.com/dperish/prettyFloat.js上的prettyFloat.js (MIT许可)


使用例子:

prettyFloat(1.111001, 3) // "1.111"
prettyFloat(1.111001, 4) // "1.111"
prettyFloat(1.1111001, 5) // "1.1111"
prettyFloat(1234.5678, 2) // "1234.57"
prettyFloat(1234.5678, 2, true) // "1,234.57" (en-us)


更新- 2018年8月


所有现代浏览器现在都支持ECMAScript国际化API,它提供了语言敏感的字符串比较、数字格式化以及日期和时间格式化。

const formatters = {
    default: new Intl.NumberFormat(),
    currency: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    whole: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 0 }),
    oneDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 1, maximumFractionDigits: 1 }),
    twoDecimal: new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 })
};

formatters.twoDecimal.format(1234.5678);  // result: "1,234.57"
formatters.currency.format(28761232.291); // result: "$28,761,232"

对于旧的浏览器,您可以使用这个填充:https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en

这里有一个可能的解决方案:

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

eval(x) --> 1.234
eval(y) --> 1.234001