AmountFormatter.java 722 B

12345678910111213141516171819202122
  1. package com.xjrsoft.common.utils;
  2. import java.math.BigDecimal;
  3. import java.text.DecimalFormat;
  4. public class AmountFormatter {
  5. public static String formatAmount(double amount) {
  6. // 将 double 转换为 BigDecimal 以避免精度问题
  7. BigDecimal bigDecimal = BigDecimal.valueOf(amount);
  8. // 判断小数点后的位数
  9. int scale = bigDecimal.scale();
  10. if (scale <= 2) {
  11. // 如果小数点后少于或等于两位,补全两位
  12. DecimalFormat df = new DecimalFormat("#.00");
  13. return df.format(amount);
  14. } else {
  15. // 如果小数点后超过两位,保留实际值
  16. return String.valueOf(amount);
  17. }
  18. }
  19. }