DecimalUtils.java 992 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package cn.com.lzt.tools;
  2. import java.math.BigDecimal;
  3. import java.text.DecimalFormat;
  4. public class DecimalUtils {
  5. public static Double ZERO = formatToDouble(0);
  6. public static BigDecimal ZERODecimal = BigDecimal.ZERO;
  7. /**
  8. * 保留2位小数
  9. * 四舍五入
  10. * */
  11. public static String formatToStr(double x) {
  12. DecimalFormat df = new DecimalFormat("#.00");
  13. return df.format(x);
  14. }
  15. /**
  16. * 保留2位小数
  17. * 四舍五入
  18. * */
  19. public static double formatToDouble(double x) {
  20. x = (double) Math.round(x * 100) / 100;
  21. return x;
  22. }
  23. /**
  24. * 保留2位小数
  25. * 指定进位类型
  26. * */
  27. public static double formatToDouble(double d ,int roundingMode) {
  28. BigDecimal b = new BigDecimal(d);
  29. d = b.setScale(2, roundingMode).doubleValue();
  30. return d;
  31. }
  32. public static BigDecimal formatToDecimal(double x) {
  33. x = (double) Math.round(x * 100) / 100;
  34. BigDecimal d = new BigDecimal(String.valueOf(x));
  35. d.setScale(2,BigDecimal.ROUND_HALF_UP);
  36. return d;
  37. }
  38. }