Search code examples
javadouble

How to create new double number with 2 numbers before and 2 numbers after dot from a previous double number?


I need help to create a new double number by selecting 2 numbers before dot and 2 numbers after dot from a previous double number.

For example:

Double number: 1054001.4032

New double number: 1.40

Double number: 2015.0634547

New double number: 15.06

Double number: 319.00056

New double number: 19.00

So far, I found instructions on splitting (which is not the case). My goal is to create a new double number as shown above.


Solution

  • Try using String.split:

    class Main {
        private static final int MAX_DIST_FROM_DECMIMAL_POINT = 2;
    
        public static double extractDouble(double num) {
            // 0. Return early if num is zero.
            if (num == 0) {
                return 0;
            }
            // 1. Cast the double into a string.
            String numStr = String.valueOf(num);
            // 2. Split the string at the decimal point into the integer and decimal parts.
            String[] parts = numStr.split("\\.");
            String intPart = parts[0];
            String decPart = parts[1];
            // 3. Extract substrings around decimal point.
            String newIntPart = intPart.substring(intPart.length() - Math.min(intPart.length(), MAX_DIST_FROM_DECMIMAL_POINT));
            String newDecPart = decPart.substring(0, Math.min(decPart.length(), MAX_DIST_FROM_DECMIMAL_POINT));
            // 4. Comine the two strings into a double.
            return Double.parseDouble(newIntPart + "." + newDecPart);
        }
    
        public static void main(String[] args) {
            double n1 = 1054001.4032;
            System.out.printf("%f => %.2f%n", n1, extractDouble(n1));
            double n2 = 2015.0634547;
            System.out.printf("%f => %.2f%n", n2, extractDouble(n2));
            double n3 = 319.00056;
            System.out.printf("%f => %.2f%n", n3, extractDouble(n3));
            double n4 = 1.2;
            System.out.printf("%f => %.2f%n", n4, extractDouble(n4));
        }
    }
    

    Output:

    1054001.403200 => 1.40
    2015.063455 => 15.06
    319.000560 => 19.00
    1.200000 => 1.20