Why was the pattern string not followed in this code?
Asked Answered
G

4

15

When following code is executed:

DecimalFormat eNotation1 = new DecimalFormat("#0.###E0");   
System.out.println(eNotation1.format(123.456789)); 

My expected output is;

1.235E2

instead,

1.2346E2

was printed.

Why was the output 1.2346E2?

I know I could have used a method like setMaximumFractionDigits() if all I wanted was to set the maximum number of digits after the decimal point, but I just really want to understand why the output was 1.2346E2

Garrotte answered 29/4, 2019 at 13:0 Comment(0)
D
15

If you want that exact format, then use the pattern 0.000E0:

DecimalFormat eNotation1 = new DecimalFormat("0.000E0");
System.out.println(eNotation1.format(123.456789));

1.235E2

As to why you are seeing your current behavior, the # placeholders are optional digits, which means that DecimalFormat is not obligated to actually use them exactly as you used them in the pattern. The only requirement appears to be that the total number of digits appearing in the scientific notation output matches. In this case, the total number of digits is five, so we get the output 1.2346E2.

Dowzall answered 29/4, 2019 at 13:21 Comment(0)
D
3

In order to fit your first pattern better i would just remove the first #. Like this you fit international unit system while keeping optional numbers after point.

DecimalFormat eNotation1 = new DecimalFormat("0.###E0");   
System.out.println(eNotation1.format(123.456789));
Danieledaniell answered 29/4, 2019 at 13:49 Comment(0)
A
2

Seems like this pattern will work as you expect

DecimalFormat eNotation1 = new DecimalFormat("0.000E0");
Antifreeze answered 29/4, 2019 at 13:13 Comment(2)
Yes DecimalFormat("0.000E0") will print 1.235E2, but I'm still wondering why the output wasn't 1.235E2 with the code segment given in the question.Garrotte
Because the difference between # and 0 in decimal Format is in existing of this digit. If you use # here there are several options of presenting this number and that's why it will work wrongly with some numbers.Antifreeze
W
1

Basically, Using 0s for your pattern causes the formatter to use the specific digits in place and convert the remaining to Exponential Notation.

Using #s for the same pattern, makes all remaining digits fit into the number of places specified, before applying exponents, meaning your specific use case will be rounded, then the remaining digits will be added to the Exponent.

Granted the Docs aren't that clear on it: https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html.

"123456.789 ###.## 123456.79 The value has three digits to the right of the decimal point, but the pattern has only two. The format method handles this by rounding up."

Wallsend answered 29/4, 2019 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.