How do I convert a double into an n-character string using exponential notation?

738 views Asked by At

I have found this vise-versa many times on SO, but never like I want it.

I want to convert a double into a string that takes up exactly n characters.

If n is, for example, 6, then


1,000,123.456 would become 1.00E6
-1,000,123.456 would become 1.0E-6
1.2345678 would become 1.2345
1,000,000,000,000 would become 1.0E12

etc.

How do I achieve that? Regards, Claas M.

P.S How do I set tabs on SO?

1

There are 1 answers

2
Shar1er80 On BEST ANSWER

If you're limiting you're exponential component to E0 to E99 (for positive exponential) and E0 to E-9 (for negative exponential), you could use a combination of DecimalFormat and Regex to format your results to be 6 characters in length.

Something like:

public static void main(String[] args) throws Exception {
    System.out.println(toSciNotation(1000123.456));         // would become 1.00E6 
    System.out.println(toSciNotation(-1123123.456));        // would become 1.1E-6 
    System.out.println(toSciNotation(1.2345678));           // would become 1.2345 
    System.out.println(toSciNotation(1000000000000L));      // would become 1.0E12
    System.out.println(toSciNotation(0.0000012345));        // would become 1.2E-6
    System.out.println(toSciNotation(0.0000000012345));     // would become 1.2E-9
    System.out.println(toSciNotation(12.12345E12));         // would become 1.2E13
}

private static String toSciNotation(double number) {
    return formatSciNotation(new DecimalFormat("0.00E0").format(number));
}

private static String toSciNotation(long number) {
    return formatSciNotation(new DecimalFormat("0.00E0").format(number));
}

private static String formatSciNotation(String strNumber) {
    if (strNumber.length() > 6) {
        Matcher matcher = Pattern.compile("(-?\\d+)(\\.\\d{2})(E-?\\d+)").matcher(strNumber);

        if (matcher.matches()) {
            int diff = strNumber.length() - 6;
            strNumber = String.format("%s%s%s", 
                    matcher.group(1),
                    // We add one back to include the decimal point
                    matcher.group(2).substring(0, diff + 1),
                    matcher.group(3)); 
        }
    }
    return strNumber;
}

Results:

1.00E6
-1.1E6
1.23E0
1.0E12
1.2E-6
1.2E-9
1.2E13