类型转换

Double强转Int,但是会存在精度不一致问题

  1. double doubleNumber = 24.04;
  2. int intPart = (int) doubleNumber;
  3. System.out.println("Double Number: " + doubleNumber);
  4. System.out.println("Integer Part: " + intPart);
  5. System.out.println("Decimal Part: " + (doubleNumber - intPart));
  6. Double Number: 24.04
  7. Integer Part: 24
  8. Decimal Part: 0.03999999999999915

字符串分隔

  1. double doubleNumber = 24.04;
  2. String doubleAsString = String.valueOf(doubleNumber);
  3. int indexOfDecimal = doubleAsString.indexOf(".");
  4. System.out.println("Double Number: " + doubleNumber);
  5. System.out.println("Integer Part: " + doubleAsString.substring(0, indexOfDecimal));
  6. System.out.println("Decimal Part: " + doubleAsString.substring(indexOfDecimal));
  7. System.out.println("Decimal Part As Int: " + Integer.parseInt(doubleAsString.substring(indexOfDecimal + 1)));
  8. Double Number: 24.04
  9. Integer Part: 24
  10. Decimal Part: .04
  11. Decimal Part As Int: 4

使用BigDecimal

  1. double doubleNumber = 24.04;
  2. BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
  3. int intValue = bigDecimal.intValue();
  4. System.out.println("Double Number: " + bigDecimal.toPlainString());
  5. System.out.println("Integer Part: " + intValue);
  6. String str = "Decimal Part: " + bigDecimal.subtract(new BigDecimal(intValue)).toPlainString();
  7. System.out.println(str);
  8. System.out.println("Decimal Part As Int: " + Integer.parseInt(str.substring(str.indexOf(".") + 1)));
  9. Double Number: 24.04
  10. Integer Part: 24
  11. Decimal Part: 0.04
  12. Decimal Part As Int: 4