[英]Java round double and get a double
I have seen numerous examples of rounding using DecimalFormat and NumberFormat but these return Strings when used. 我已经看到了许多使用DecimalFormat和NumberFormat进行四舍五入的示例,但是使用它们时它们返回String。 Yes I know that one can use parse to get the number back, however this adds complexity.
是的,我知道可以使用解析来获取数字,但这会增加复杂性。
So how does one round a double to a given precision and get a double back with as few midsteps as possible? 那么,如何将双精度圆整到给定的精度并以尽可能少的中间步数获得双精度?
There's no real way to do that. 没有真正的方法可以做到这一点。 You could do the old (X*10^N)/10^N trick, I suppose, but you may not get the arbitrary precision you want.
我想,您可以做旧的(X * 10 ^ N)/ 10 ^ N技巧,但是您可能无法获得想要的任意精度。 That's the trick with floating point numbers.
这就是浮点数的窍门。 If you want arbitrary precision, you need to use BigDecimal.
如果要任意精度,则需要使用BigDecimal。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.