2011-05-29 97 views
20
double d = 4.321562; 

有没有一种简单的方法从d上自己提取0.321562?我试着在数学课上看,但没有运气。如果这可以完成而不转换为字符串或转换为其他任何东西,甚至更好。如何获取小数点后的数字? (java)

回答

25

好了,你可以使用:

double x = d - Math.floor(d); 

注意的是,由于该二进制浮点的工作方式,不会给你确切 0.321562,作为原始值不准确 4.321562。如果您对精确数字非常感兴趣,则应该使用BigDecimal

+1

不要使用此,使铸件改为:'X - (INT)x'。铸造将正面和负面的数字都能正常工作。否则,'Math.floor()'将使用“小于或等于参数”的最正(最接近正无穷大)整数值。例如:'-123.25 - (int)( - 123.25)'将产生-0.25,所以你可以决定如何处理符号。 'Math.floor()'的使用将给出'0.75'的正数 – 2015-12-27 18:35:18

+0

@Bagzerg:同意,虽然强制转换将比强制转换为double要好,以处理int范围之外的值。当我有机会时将编辑提及两者。 – 2015-12-27 19:19:37

25

另一种不使用数学就可以得到分数的方法是投射很长时间。

double x = d - (long) d; 

当您打印double了toString将执行四舍五入,所以你看不到任何舍入误差少量。但是,删除整数部分时,舍入不再充分,舍入误差变得明显。

解决此问题的方法是自己做四舍五入或使用BigDecimal,它允许您控制四舍五入。

double d = 4.321562; 
System.out.println("Double value from toString " + d); 
System.out.println("Exact representation " + new BigDecimal(d)); 
double x = d - (long) d; 
System.out.println("Fraction from toString " + x); 
System.out.println("Exact value of fraction " + new BigDecimal(x)); 
System.out.printf("Rounded to 6 places %.6f%n", x); 
double x2 = Math.round(x * 1e9)/1e9; 
System.out.println("After rounding to 9 places toString " + x2); 
System.out.println("After rounding to 9 places, exact value " + new BigDecimal(x2)); 

打印

Double value from toString 4.321562 
Exact representation 4.321562000000000125510268844664096832275390625 
Fraction from toString 0.3215620000000001 
Exact value of fraction 0.321562000000000125510268844664096832275390625 
Rounded to 6 places 0.321562 
After rounding to 9 places toString 0.321562 
After rounding to 9 places, exact value 0.32156200000000001448796638214844278991222381591796875 
+2

+1为准确。 – David 2011-05-29 09:08:25

+0

这就是答案 – 2016-04-21 19:40:24

+0

@ diegomatos-keke感谢您的支持。 – 2016-04-21 19:41:41

6

使用模:

double d = 3.123 % 1; 
assertEquals(0.123, d,0.000001);