获取 a 的小数部分的一种简单方法double
是使用模运算符%
. 但是,您必须考虑浮点运算不精确的事实。例如,
System.out.println(12.1 % 1); // outputs 0.09999999999999964
System.out.println(12.99 % 1); // outputs 0.9900000000000002
如果你想得到两个十进制数字int
,这就是我认为你要问的,你可以做到这一点,掩盖浮点问题,如下所示:
System.out.println(Math.round((12.1 % 1) * 100)); // outputs 10
System.out.println(Math.round((12.99 % 1) * 100)); // outputs 99
但是,您应该考虑BigDecimal
沿着您开始的路径走得更远,它使用任意精度算术。你可以这样做:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE)); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE)); // outputs 0.99
如果像以前一样,您想要两个十进制数字,您可以这样做:
System.out.println(new BigDecimal("12.1").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.1
System.out.println(new BigDecimal("12.99").remainder(BigDecimal.ONE).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP).intValue()); // outputs 0.99
Note that there a couple of differences between these last two methods and the first two: they preserve the sign of the argument, so if you use the final example for -12.99, you'll get -99 back, and they treat the fractional part of an integer as 1, so if you use the final example for 12, you'll get 100 back.