如何获取小数点后的数字? (java)
double d = 4.321562;
有没有一种简单的方法可以从 d 中单独提取 0.321562 ?我尝试查看数学课,但没有成功。如果这可以在不转换为字符串或转换为其他任何内容的情况下完成,那就更好了。
double d = 4.321562;
Is there an easy way to extract the 0.321562 on it's own from d? I tried looking in the math class but no luck. If this can be done without converting to string or casting to anything else, even better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,您可以使用:
请注意,由于二进制浮点的工作方式,这不会给您准确 0.321562,因为原始值不准确 4.321562 。如果您确实对精确数字感兴趣,则应该使用 BigDecimal。
Well, you can use:
Note that due to the way that binary floating point works, that won't give you exactly 0.321562, as the original value isn't exactly 4.321562. If you're really interested in exact digits, you should use
BigDecimal
instead.另一种不使用 Math 来获取分数的方法是转换为 long。
当您打印
double
时,toString 将执行少量舍入,因此您不会看到任何舍入错误。但是,当删除整数部分时,舍入就不再足够,并且舍入误差变得明显。解决这个问题的方法是自己进行舍入或使用 BigDecimal,它允许您控制舍入。
注意
:
double
的精度有限,如果不使用适当的舍入,您会发现表示问题逐渐出现。这种情况可能发生在您使用double
esp 数字进行的任何计算中,这些数字不是 2 的幂的精确总和。Another way to get the fraction without using Math is to cast to a long.
When you print a
double
the toString will perform a small amount of rounding so you don't see any rounding error. However, when you remove the integer part, the rounding is no longer enough and the rounding error becomes obvious.The way around this is to do the rounding yourself or use BigDecimal which allows you to control the rounding.
prints
NOTE:
double
has limited precision and you can see representation issue creep in if you don't use appropriate rounding. This can happen in any calculation you use withdouble
esp numbers which are not an exact sum of powers of 2.使用模:
Use modulo: