JavaScript:四舍五入到多个小数位,但去除多余的零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7312468/
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
JavaScript: Round to a number of decimal places, but strip extra zeros
提问by Nathan
Here's the scenario: I'm getting .9999999999999999
when I should be getting 1.0
.
I can afford to lose a decimal place of precision, so I'm using .toFixed(15)
, which kind of works.
场景是这样的:.9999999999999999
当我应该得到1.0
.
我可以承受精度的小数位丢失,所以我使用.toFixed(15)
, 哪种有效。
The rounding works, but the problem is that I'm given 1.000000000000000
.
Is there a way to round to a number of decimal places, but strip extra whitespace?
舍入有效,但问题是我得到了1.000000000000000
.
有没有办法四舍五入到小数位,但去掉多余的空格?
Note: .toPrecision
isn't what I want; I only want to specify how many numbers after the decimal point.
Note 2: I can't just use .toPrecision(1)
because I need to keep the high precision for numbers that actually have data after the decimal point. Ideally, there would be exactly as many decimal places as necessary (up to 15).
注意:.toPrecision
不是我想要的;我只想指定小数点后有多少个数字。
注2:我不能只使用,.toPrecision(1)
因为我需要保持小数点后实际有数据的数字的高精度。理想情况下,小数位数将与所需的一样多(最多 15 位)。
回答by Gus
>>> parseFloat(0.9999999.toFixed(4));
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0
回答by Nachshon Schwartz
Yes, there is a way. Use parseFloat()
.
是的,有办法。使用parseFloat()
.
parseFloat((1.005).toFixed(15)) //==> 1.005
parseFloat((1.000000000).toFixed(15)) //==> 1
See a live example here: http://jsfiddle.net/nayish/7JBJw/
在此处查看现场示例:http: //jsfiddle.net/nayish/7JBJw/
回答by Jiri Kriz
As I understand, you want to remove the trailing zeros in the string that you obtained via toFixed()
. This is a pure string operation:
据我了解,您想删除通过toFixed()
. 这是一个纯字符串操作:
var x = 1.1230000;
var y = x.toFixed(15).replace(/0+$/, ""); // ==> 1.123
回答by kennebec
Number(n.toFixed(15)) or +(n.toFixed(15))
will convert the 15 place decimal string to a number, removing trailing zeroes.
Number(n.toFixed(15)) or +(n.toFixed(15))
将 15 位十进制字符串转换为数字,删除尾随零。
回答by C. J.
If you cast the return value to a number, those trailing zeroes will be dropped. This is also less verbose than parseFloat()
is.
如果将返回值转换为数字,则将删除那些尾随零。这也没有那么冗长parseFloat()
。
+(4.55555).toFixed(2);
//-> 4.56
+(4).toFixed(2);
//-> 4
This uses the unary + operator, so if using this as part of a string operation you need to have an infix + before it: var n=0.9999999999999999; console.log('output ' + +n.toFixed(2));
. FYI a unary + in front of a string converts it to a Number. From MDN: Unary + can:
这使用一元 + 运算符,因此如果将其用作字符串操作的一部分,您需要在它之前有一个中缀 + :var n=0.9999999999999999; console.log('output ' + +n.toFixed(2));
。仅供参考,字符串前面的一元 + 会将其转换为数字。来自 MDN:一元 + 可以:
convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
转换整数和浮点数的字符串表示,以及非字符串值 true、false 和 null。支持十进制和十六进制(“0x”前缀)格式的整数。支持负数(但不支持十六进制)。如果它无法解析特定值,它将评估为 NaN。
回答by super
Mmmm, a little different answer, for cross browser too:
嗯,有点不同的答案,也适用于跨浏览器:
function round(x, n) {
return Math.round(x * Math.pow(10, n)) / Math.pow(10, n)
}
回答by Jenna Zeigen
None of these really got me what I was looking for based on the question title, which was, for example, for 5.00 to be 5 and 5.10 to be 5.1. My solution was as follows:
根据问题标题,这些都没有真正让我得到我想要的东西,例如,5.00 为 5,5.10 为 5.1。我的解决方案如下:
num.toFixed(places).replace(/\.?0+$/, '')
'5.00'.replace(/\.?0+$/, '') // 5
'5.10'.replace(/\.?0+$/, '') // 5.1
'5.0000001'.replace(/\.?0+$/, '') // 5.0000001
'5.0001000'.replace(/\.?0+$/, '') // 5.0001
Note: The regex only works if places > 0
注意:正则表达式仅适用于 places > 0
P.S. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
PS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
回答by Kevrone
There is a better method which keeps precision and also strips the zeros. This takes an input number and through some magic of casting will pull off any trailing zeros. I've found 16 to be the precision limit for me which is pretty good should you not be putting a satellite on pluto.
有一种更好的方法可以保持精度并去除零。这需要一个输入数字,并通过一些魔法转换将消除任何尾随零。我发现 16 对我来说是精度限制,如果你不在冥王星上放置卫星,这很好。
function convertToFixed(inputnum)
{
var mynum = inputnum.toPrecision(16);
//If you have a string already ignore this first line and change mynum.toString to the inputnum
var mynumstr = mynum.toString();
return parseFloat(mynumstr);
}
alert(convertToFixed(6.6/6));
回答by bvdb
The toFixed()
methodformats a number
using fixed-point notation, and returns a string
.
该toFixed()
方法number
使用定点表示法格式化 a ,并返回 a string
。
It applies a half-up roundingstrategy.
它采用半向上舍入策略。
(0.124).toFixed(2); // returns 0.12
(0.125).toFixed(2); // returns 0.13
As you described, it will indeed also result in (potentially unnecessary) trailing zeroes sometimes.
正如您所描述的,有时它确实也会导致(可能不必要的)尾随零。
(0.001).toFixed(2); // returns 0.00
You may not want to get rid of those trailing zeroes, essentially you could just convert it back to a number
. There are many ways to do this.
您可能不想摆脱那些尾随零,基本上您可以将其转换回number
. 有很多方法可以做到这一点。
+(0.001).toFixed(2); // the shortest
For an overview, of the different methods to convert strings to numbers, please check thisquestion, which has some excellent answers.
有关将字符串转换为数字的不同方法的概述,请查看此问题,其中有一些很好的答案。