JavaScript:四舍五入到小数位,但去掉多余的零 [英] JavaScript: Round to a number of decimal places, but strip extra zeros

查看:25
本文介绍了JavaScript:四舍五入到小数位,但去掉多余的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况如下:我得到 .9999999999999999 而我应该得到 1.0.
我可以承受丢失小数点的精度,所以我使用 .toFixed(15),这很有效.

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.

四舍五入有效,但问题是我得到了 1.000000000000000.
有没有办法四舍五入到小数位,但去掉多余的空格?

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?

注意:.toPrecision 不是我想要的;我只想指定小数点后有多少个数字.
注意 2:我不能只使用 .toPrecision(1) 因为我需要为小数点后实际有数据的数字保持高精度.理想情况下,小数位数应与需要的位数一样多(最多 15 位).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆