将双分为“整数”和“整数”的最佳方式是什么?分数"在java中 [英] What is the best way to separate double into two parts "integer & fraction" in java
本文介绍了将双分为“整数”和“整数”的最佳方式是什么?分数"在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过以下方法分离5.6(例如):
I have tried to separate 5.6 (for example) by the following method:
private static double[] method(double d)
{
int integerPart = 0;
double fractionPart = 0.0;
integerPart = (int) d;
fractionPart = d - integerPart;
return new double[]{integerPart, fractionPart};
}
但是我得到的是:
[0] = 5.0
[1] = 0.5999999999999996
您是否有任何建议,无需将号码转换为字符串?
Do you have any suggestion about doing this without converting the number to string?
推荐答案
使用 BigDecimal
/ a>做同样的计算。 (使用双精度因为它的表示而具有精确的问题)。
Use BigDecimal
to do that same calculation. (using doubles has precision problems because of its representation).
- 使用
构造新的BigDecimal(String.valueOf yourDouble))
(这仍然是通过字符串,但部分不通过字符串操作分隔) - 使用
bd.subtract(新的BigDecimal(bd.intValue())
确定分数
- Construct it with
new BigDecimal(String.valueOf(yourDouble))
(this is still going through string, but the parts are not separated via string manipulation) - use
bd.subtract(new BigDecimal(bd.intValue())
to determine the fraction
这篇关于将双分为“整数”和“整数”的最佳方式是什么?分数"在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文