Today's test found that there is a decimal precision problem in the message passing process.
It is required to keep 6 decimal places, and it is not enough to be supplemented with 0. As a result, I didn’t pay attention to it during development. After the 0.123456 format is controlled, it becomes .123456. Although there is no difference from the point of view of the value, the downstream people who receive the message do not recognize it. . . . . .
The following common rounding methods are summarized:
public static void main(String[] args) { System.out.println(getNum(0.23656,"#.0000",false));//.2365 is not rounded, omitted when the integer part is 0 System.out.println(getNum(0.23656,"0.0000",false));//0.2365 is not rounded, and the integer part is not omitted when it is 0 System.out.println(getNum(0.23656,"0.0000",true));//0.2366 for rounding System.out.println(getNum(0.236,"0.0000",true));//0.2366 for rounding off the fractional part with zeros // // System.out.println(getNum2(0.23456,3));//Exact third decimal place, rounded up //System.out.println(getNum3(0.2345,3,false));//0.234 // System.out.println(getNum4(0.2345,3,false));//0.234 // System.out.println(getNum4(0.2345,3,true));//0.235 // System.out.println(getNum4(0.23,3,false));//0.23 without zero padding } public static String getNum(double str,String pattern,boolean flag){ DecimalFormat format = new DecimalFormat(pattern);//Keep three decimal places if(flag) { format.setRoundingMode(RoundingMode.UP);//Round } else { format.setRoundingMode(RoundingMode.DOWN);//No rounding } return format.format(str); } public static String getNum2(double str , int decima) { long n = 1; for(int i = 1 ; i <= decima; i++ ) n *= 10; return String.valueOf((int)(str * n +0.5) / (n * 1.0)); } public static double getNum3(double str,int point, boolean flag){ BigDecimal b = new BigDecimal(str); if(flag) { return b.setScale(point, BigDecimal.ROUND_HALF_UP).doubleValue(); } return b.setScale(point, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } public static String getNum4(double d,int point,boolean flag) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(point); // keep the number of decimal places if(flag){ nf.setRoundingMode(RoundingMode.UP);//Round up }else { nf.setRoundingMode(RoundingMode.DOWN);// do not round } return nf.format(d); }