类型转换
Double强转Int,但是会存在精度不一致问题
double doubleNumber = 24.04;
int intPart = (int) doubleNumber;
System.out.println("Double Number: " + doubleNumber);
System.out.println("Integer Part: " + intPart);
System.out.println("Decimal Part: " + (doubleNumber - intPart));
Double Number: 24.04
Integer Part: 24
Decimal Part: 0.03999999999999915
字符串分隔
double doubleNumber = 24.04;
String doubleAsString = String.valueOf(doubleNumber);
int indexOfDecimal = doubleAsString.indexOf(".");
System.out.println("Double Number: " + doubleNumber);
System.out.println("Integer Part: " + doubleAsString.substring(0, indexOfDecimal));
System.out.println("Decimal Part: " + doubleAsString.substring(indexOfDecimal));
System.out.println("Decimal Part As Int: " + Integer.parseInt(doubleAsString.substring(indexOfDecimal + 1)));
Double Number: 24.04
Integer Part: 24
Decimal Part: .04
Decimal Part As Int: 4
使用BigDecimal
double doubleNumber = 24.04;
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
int intValue = bigDecimal.intValue();
System.out.println("Double Number: " + bigDecimal.toPlainString());
System.out.println("Integer Part: " + intValue);
String str = "Decimal Part: " + bigDecimal.subtract(new BigDecimal(intValue)).toPlainString();
System.out.println(str);
System.out.println("Decimal Part As Int: " + Integer.parseInt(str.substring(str.indexOf(".") + 1)));
Double Number: 24.04
Integer Part: 24
Decimal Part: 0.04
Decimal Part As Int: 4