12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package com.slibra.common;
- import com.alibaba.fastjson2.JSON;
- import com.alibaba.fastjson2.JSONArray;
- import com.slibra.common.utils.StringUtils;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.util.*;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- import static com.slibra.common.constant.MyConstants.INT_2;
- public class DecimalUtils {
- public static BigDecimal getAbs(BigDecimal req){
- if(Objects.isNull(req))
- return null;
- return req.abs();
- }
- public static BigDecimal getAbsAndScale(BigDecimal req, int length){
- if(Objects.isNull(req))
- return null;
- return req.abs().setScale(length, RoundingMode.DOWN);
- }
- /**
- * 处理字符串类型的数值 取绝对值并保持N位小数。
- * @param req
- * @param length
- * @return
- */
- public static String getAbsAndScaleStr(String req, int length){
- if(StringUtils.isBlank(req))
- return null;
- return new BigDecimal(req).abs().setScale(length, RoundingMode.DOWN).toString();
- }
- public static String getAbsForArray(String list, int length) {
- if (StringUtils.isBlank(list)) {
- return null;
- }
- return JSONArray.parseArray(list, BigDecimal.class).stream().map(num -> getAbsAndScale(num, length)).collect(Collectors.toList()).toString();
- }
- public static void main(String[] args) {
- // System.out.println(getAbsAndScale(null, 3));
- // System.out.println(getAbsAndScale(new BigDecimal("33.33333"), 3));
- // System.out.println(getAbsAndScale(new BigDecimal("-33.33333"), 3));
- // List<Double> list = new ArrayList<>();
- // list.add(1.1D);
- // list.add(1.2D);
- // list.add(1.3D);
- // System.out.println(list.toString());
- // System.out.println(JSON.toJSONString(list));
- //
- // // System.out.println(getAbsForArray("a", 1));
- //
- // System.out.println(new BigDecimal(1.1).divide(new BigDecimal(1.3), 0, RoundingMode.HALF_UP));
- // System.out.println(DecimalUtils.getAbsAndScale(new BigDecimal("3486.000000"), INT_2));
- List<Integer> arr = new ArrayList<>();
- arr.add(1);
- arr.add(2);
- OptionalDouble average = arr.stream().mapToInt(Integer::intValue).average();
- System.out.println(average.getAsDouble());
- }
- }
|