JavaScript:舍入到小数位数,但是去掉额外的零 [英] JavaScript: Round to a number of decimal places, but strip extra zeros
问题描述
下面是这个场景:当我得到 1.0
时,得到 .9999999999999999
b $ b我可以承受失去一个小数位的精度,所以我使用 .toFixed(15)
,这种工作。
四舍五入工作,但问题是,我给了 1.000000000000000
。
有没有办法要舍去许多小数位,但要多加一些空格?
注意: .toPrecision
不是我想要的;我只想指定小数点后的数字。
注意2:我不能只用 .toPrecision(1)
因为我需要保持小数点后实际有数据的数字的高精度。理想情况下,将会有必要的小数位(至多15)。
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0
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.
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?
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).
>>> parseFloat(0.9999999.toFixed(4));
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0
这篇关于JavaScript:舍入到小数位数,但是去掉额外的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!