Javascript 从数字中删除无关紧要的尾随零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3612744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove insignificant trailing zeros from a number?
提问by Steven
Have I missed a standard API call that removes trailing insignificant zeros from a number?
我是否错过了从数字中删除尾随无关紧要的零的标准 API 调用?
Ex.
前任。
var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001
Number.toFixed() and Number.toPrecision() are not quite what I'm looking for.
Number.toFixed() 和 Number.toPrecision() 并不是我想要的。
采纳答案by Cristian Sanchez
If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.
如果将其转换为字符串,则不会显示任何尾随零,这些零一开始就不会存储在变量中,因为它是作为数字创建的,而不是字符串。
var n = 1.245000
var noZeroes = n.toString() // "1.245"
回答by Gary
I had a similar instance where I wanted to use .toFixed()where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.
我有一个类似的例子,我想.toFixed()在必要的地方使用,但我不想要填充。所以我最终将 parseFloat 与 toFixed 结合使用。
toFixed without padding
toFixed 无填充
parseFloat(n.toFixed(4));
Another option that does almost the same thing
This answer may help your decision
另一个几乎做同样事情的选项
这个答案可能会帮助你做出决定
Number(n.toFixed(4));
toFixedwill round/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:
toFixed将数字舍入/填充到特定长度,但也将其转换为字符串。将其转换回数字类型不仅会使数字在算术上使用更安全,而且还会自动删除任何尾随 0。例如:
var n = "1.234000";
n = parseFloat(n);
// n is 1.234 and in number form
Because even if you define a number with trailing zeros they're dropped.
因为即使您定义了一个带有尾随零的数字,它们也会被删除。
var n = 1.23000;
// n == 1.23;
回答by w00t
I first used a combination of matti-lyra and gary's answers:
我首先结合使用了 matti-lyra 和 gary 的答案:
r=(+n).toFixed(4).replace(/\.0+$/,'')
Results:
结果:
- 1234870.98762341: "1234870.9876"
- 1230009100: "1230009100"
- 0.0012234: "0.0012"
- 0.1200234: "0.12"
- 0.000001231: "0"
- 0.10001: "0.1000"
- "asdf": "NaN" (so no runtime error)
- 1234870.98762341:“1234870.9876”
- 1230009100:“1230009100”
- 0.0012234:“0.0012”
- 0.1200234:“0.12”
- 0.000001231:“0”
- 0.10001:“0.1000”
- "asdf": "NaN"(所以没有运行时错误)
The somewhat problematic case is 0.10001. I ended up using this longer version:
有点问题的情况是 0.10001。我最终使用了这个更长的版本:
r = (+n).toFixed(4);
if (r.match(/\./)) {
r = r.replace(/\.?0+$/, '');
}
- 1234870.98762341: "1234870.9876"
- 1230009100: "1230009100"
- 0.0012234: "0.0012"
- 0.1200234: "0.12"
- 0.000001231: "0"
- 0.10001: "0.1"
- "asdf": "NaN" (so no runtime error)
- 1234870.98762341:“1234870.9876”
- 1230009100:“1230009100”
- 0.0012234:“0.0012”
- 0.1200234:“0.12”
- 0.000001231:“0”
- 0.10001:“0.1”
- "asdf": "NaN"(所以没有运行时错误)
Update: And this is Gary's newer version (see comments):
更新:这是加里的新版本(见评论):
r=(+n).toFixed(4).replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'')
This gives the same results as above.
这给出了与上面相同的结果。
回答by C. J.
The toFixedmethod will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.
toFixed如有必要,该方法将进行适当的舍入。它还会添加尾随零,这并不总是理想的。
(4.55555).toFixed(2);
//-> "4.56"
(4).toFixed(2);
//-> "4.00"
If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.
如果将返回值转换为数字,则将删除那些尾随零。这是一种比自己进行四舍五入或截断数学运算更简单的方法。
+(4.55555).toFixed(2);
//-> 4.56
+(4).toFixed(2);
//-> 4
回答by dperish
I had the basically the same requirement, and found that there is no built-in mechanism for this functionality.
我有基本相同的要求,并发现此功能没有内置机制。
In addition to trimming the trailing zeros, I also had the need to round off and format the output for the user's current locale (i.e. 123,456.789).
除了修剪尾随零之外,我还需要根据用户的当前语言环境(即 123,456.789)对输出进行四舍五入和格式化。
All of my work on this has been included as prettyFloat.js (MIT Licensed) on GitHub: https://github.com/dperish/prettyFloat.js
我在这方面的所有工作都包含在 GitHub 上的 prettyFloat.js(MIT 许可):https: //github.com/dperish/prettyFloat.js
Usage Examples:
用法示例:
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)
Updated - August, 2018
更新 - 2018 年 8 月
All modern browsers now support the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting.
所有现代浏览器现在都支持ECMAScript 国际化 API,它提供语言敏感的字符串比较、数字格式以及日期和时间格式。
let 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: ",761,232"
For older browsers, you can use this polyfill: https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en
对于较旧的浏览器,您可以使用此 polyfill:https://cdn.polyfill.io/v2/polyfill.min.js ?features =Intl.~locale.en
回答by Howard
How about just multiplying by one like this?
像这样乘以一怎么样?
var x = 1.234000*1; // becomes 1.234
var y = 1.234001*1; // stays as 1.234001
回答by Amit Panasara
You can try this one to minify floating numbers
你可以试试这个来缩小浮点数
var n = 0.0000;
n = parseFloat(n.toString());
//output n = 0;
// n = 3.14000; --> n = 3.14;
回答by Jo?o Costa
Pure regex answer
纯正则表达式答案
n.replace(/(\.[0-9]*[1-9])0+$|\.0*$/,'');
I wonder why no one gave one!
我想知道为什么没有人给一个!
回答by megasnort
I needed to solve this problem too when Django was displaying Decimal type values in a text field. E.g. when '1' was the value. It would show '1.00000000'. If '1.23' was the value, it would show '1.23000000' (In the case of a 'decimal_places' setting of 8)
当 Django 在文本字段中显示 Decimal 类型值时,我也需要解决这个问题。例如,当 '1' 是值时。它会显示“1.00000000”。如果“1.23”是值,它将显示“1.23000000”(在“decimal_places”设置为 8 的情况下)
Using parseFloatwas not an option for me since it is possible it does not return the exact same value. toFixedwas not an option since I did not want to round anything, so I created a function:
使用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;
}
回答by Devon
None of these solutions worked for me for very small numbers. http://numeraljs.com/solved this for me.
这些解决方案都不适用于非常小的数字。 http://numeraljs.com/为我解决了这个问题。
parseFloat(0.00000001.toFixed(8));
// 1e-8
numeral(0.00000001).format('0[.][00000000]');
// "0.00000001"

