Keep decimal places

Keywords: Java github

Keep decimal places

Here I use two methods, the first is to use BigDecimal, and the second is to use DecimalFormat.

The first method:
Usage: pass in the double value and return a String type

 public static String keep_two_decimals(double number){
        BigDecimal bigDecimal   =   new   BigDecimal(number);
        double  s  =   bigDecimal.setScale(2).doubleValue();
        return String.valueOf(s);
    }

Among them, you can set it by yourself according to the requirements, and the default method is rounding

 setScale(2);//It means that 2 decimal places are reserved, and the default rounding method is used 

 setScale(2,BigDecimal.ROUND_DOWN);//Directly delete the extra decimal places 11.116 = 11.11

 setScale(2,BigDecimal.ROUND_UP);//If the adjacent bit is not zero, carry directly; if the adjacent bit is zero, carry not. 11.114 = 11.12

 setScale(2,BigDecimal.ROUND_HALF_UP);//Round to 2.335 = 2.33, 2.3351 = 2.34

 setScaler(2,BigDecimal.ROUND_HALF_DOWN);//Rounding: 2.335 ~ 2.33, 2.3351 ~ 2.34, 11.117 ~ 11.12

The second method:

 public static String keepTwoByDecimalFormat(double number) {
        DecimalFormat df = new java.text.DecimalFormat("#.00");
        String s = df.format(number);//Default String.format will automatically round
        return s;
    }

It should be noted that String.format will be automatically rounded. If the background does not return accurate numbers in terms of amount display, you need to pay attention when using the method of keeping two decimal places. If each person has 0.01 yuan more than 100 million users, the company will lose 1 million yuan (how expensive...)

Here, we also learn the rules used by predecessors to judge by removing the redundant 0 of double string

 public static String doubleTypeRep(String str) {
        if (!str.contains(".")) {
            return str;
        }
        String[] strArr = str.split("\\.");
        String end = strArr[1];
        if (end.matches("[0]{2}")) {
            return strArr[0];
        } else if (end.matches("[0-9][0]")) {
            return str.substring(0, str.length() - 1);
        } else if (end.matches("[0]")) {
            return strArr[0];
        }

        return str;

    }

use:

 public static String keepTwoByDecimalFormat(double number) {
        DecimalFormat df = new java.text.DecimalFormat("#.00");
        String s = df.format(number);//Default String.format will automatically round
        return doubleTypeRep(s);
    }

In this way, if there is a number like 234.00234.10, it will return 234234.1 when it returns

Github address

Posted by DefunctExodus on Sat, 02 May 2020 11:50:11 -0700