Java retains three significant digits after the decimal point and rounds

problem background

We usually encounter a problem in our daily development and processing: it is impossible to determine how many 0s pass through the decimal point before a valid number will appear. For example: 0.00097213, the valid number 9 appears after three zeros, and: 0.1234 is the valid number that appears directly. For numbers, in most cases, we need to keep how many digits, for example, three digits are reserved for processing. The processing here generally includes warehousing operations or making some data kanbans or reports. It is impossible for some numbers to be dragged for a long time, and some numbers are endlessly looped.

Solutions

If we observe the overall situation of decimals, we can summarize decimals as having significant digits after n zeros, and the number of significant digits is greater than zero.
The most intuitive method is the form of regular matching. According to the above summary, write a regular expression that searches for the first number of 1 to 9 after the decimal point or 0 to find the first number that is not 0. Here is the code:

public static Double decimalProcessing(double decimal) {
    
    
        BigDecimal decimalValue = new BigDecimal(String.valueOf(decimal));
        String decimalString = String.valueOf(decimal);

        Pattern pattern = Pattern.compile("(?<=(\\.|0))([1-9])");
        Matcher matcher = pattern.matcher(decimalString);
        int firstNonZeroPosition = 0;
        if (matcher.find()) {
    
    
            firstNonZeroPosition = matcher.start(2) - matcher.start(1);
        }

        MathContext mc = new MathContext(firstNonZeroPosition + 2);
        BigDecimal processedDecimal = decimalValue.divide(BigDecimal.ONE, mc);
        return processedDecimal.doubleValue();
    }

First, convert the decimal to BIgDecimal type, which is convenient for more accurate floating-point calculation and rounding operations, and then convert it to a string, and use the written regex to match.
After finding the position of the first non-zero number, use match.start() to calculate the position of the first non-zero number relative to the decimal point, and then create a MathContext instance based on this position to specify the number of significant digits reserved. Here we set 3 digits, so it is +3 operation.
Finally, use divide to divide the decimal by 1 and use MathContext for rounding, and finally type conversion to output the number.
In this way, we have completed the process of retaining three significant figures after the decimal point and rounding.

Guess you like

Origin blog.csdn.net/qq_43881656/article/details/130528520