DecimalUtils.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.slibra.common;
  2. import com.alibaba.fastjson2.JSON;
  3. import com.alibaba.fastjson2.JSONArray;
  4. import com.slibra.common.utils.StringUtils;
  5. import java.math.BigDecimal;
  6. import java.math.RoundingMode;
  7. import java.util.*;
  8. import java.util.stream.Collectors;
  9. import java.util.stream.Stream;
  10. import static com.slibra.common.constant.MyConstants.INT_2;
  11. public class DecimalUtils {
  12. public static BigDecimal getAbs(BigDecimal req){
  13. if(Objects.isNull(req))
  14. return null;
  15. return req.abs();
  16. }
  17. public static BigDecimal getAbsAndScale(BigDecimal req, int length){
  18. if(Objects.isNull(req))
  19. return null;
  20. return req.abs().setScale(length, RoundingMode.DOWN);
  21. }
  22. /**
  23. * 处理字符串类型的数值 取绝对值并保持N位小数。
  24. * @param req
  25. * @param length
  26. * @return
  27. */
  28. public static String getAbsAndScaleStr(String req, int length){
  29. if(StringUtils.isBlank(req))
  30. return null;
  31. return new BigDecimal(req).abs().setScale(length, RoundingMode.DOWN).toString();
  32. }
  33. public static String getAbsForArray(String list, int length) {
  34. if (StringUtils.isBlank(list)) {
  35. return null;
  36. }
  37. return JSONArray.parseArray(list, BigDecimal.class).stream().map(num -> getAbsAndScale(num, length)).collect(Collectors.toList()).toString();
  38. }
  39. public static void main(String[] args) {
  40. // System.out.println(getAbsAndScale(null, 3));
  41. // System.out.println(getAbsAndScale(new BigDecimal("33.33333"), 3));
  42. // System.out.println(getAbsAndScale(new BigDecimal("-33.33333"), 3));
  43. // List<Double> list = new ArrayList<>();
  44. // list.add(1.1D);
  45. // list.add(1.2D);
  46. // list.add(1.3D);
  47. // System.out.println(list.toString());
  48. // System.out.println(JSON.toJSONString(list));
  49. //
  50. // // System.out.println(getAbsForArray("a", 1));
  51. //
  52. // System.out.println(new BigDecimal(1.1).divide(new BigDecimal(1.3), 0, RoundingMode.HALF_UP));
  53. // System.out.println(DecimalUtils.getAbsAndScale(new BigDecimal("3486.000000"), INT_2));
  54. List<Integer> arr = new ArrayList<>();
  55. arr.add(1);
  56. arr.add(2);
  57. OptionalDouble average = arr.stream().mapToInt(Integer::intValue).average();
  58. System.out.println(average.getAsDouble());
  59. }
  60. }