将浮点数/小数精确舍入到小数点后 3 位?
我知道有很多问题要求这个,但我已经尝试了很多解决方案,但似乎没有一个能完全按照我需要的方式工作!
大多数解决方案都有效,但是在我的测试数据中,我有 float
:0.08095238095238096
如果我将其四舍五入到 4,我似乎会得到; 0.081
当我需要 0.0809
并且不四舍五入最后一个位置时。
另外,对于这种类型的数字,我最好使用 float 还是 double ?
谢谢
I know there are many questions asking for this, but I have tried quite a few of the solutions but none seem to work exactly how I need it!
Most solutions work, however in my test data I have the float
: 0.08095238095238096
If I round this to 4 I seem to get; 0.081
when I need to have 0.0809
and not rounded up that last place.
Also am I best using float or double for this type of number?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎想要向下舍入到小数点后四位,而不是向上舍入一半。
或者
我假设你的意思是你想要 d = 0.0809 而不是 0.809。
也许您正在考虑 3 个有效数字,这是一个更难的问题。
最好使用
double
或BigDecimal
而不是float
,除非你有充分的理由。顺便说一句:清楚地了解自己想要什么是很有用的,否则找到它会更加困难。 ;)
You appear to want to round down to FOUR decimal places instead of rounding half up.
or
I assume you mean you want d = 0.0809 instead of 0.809.
Perhaps you are thinking of 3 significant digits which is a harder problem.
Its best to use
double
orBigDecimal
instead offloat
unless you have a very good reason.BTW: It is useful to have a clear idea of what you want, otherwise its going to be much harder to find it. ;)