Java – How do I determine the maximum size of a DecimalFormat before displaying it exponentially?

How do I determine the maximum size of a DecimalFormat before displaying it exponentially?… here is a solution to the problem.

How do I determine the maximum size of a DecimalFormat before displaying it exponentially?

The number I display in EditText can reach 20 characters + 4 decimal places before it is too long. I want the number to be longer than the one displayed with de exposant at the end so that it doesn’t get truncated.

For example: 123456789 will be displayed as-is
123456789123456789123456 is too long and will be displayed as 1.123456789E8 (as an example only!)

I tested this :

DecimalFormat df = new DecimalFormat("#.####");
df.setMaximumIntegerDigits(20);

But after 20char, the numbers are not displayed correctly. For example: 123456789123456789123456 becomes 56789123456789123456 (relay 4 the first digit. )

Thanks!

Solution

Decimal Formater java doc describes how to handle exponents.

Scientific Notation

Numbers in scientific notation are
expressed as the product of a mantissa
and a power of ten, for example, 1234
can be expressed as 1.234 x 10^3. The
mantissa is often in the range 1.0 <=
x < 10.0, but it need not be.
DecimalFormat can be instructed to
format and parse scientific notation
only via a pattern; there is currently
no factory method that creates a
scientific notation format. In a
pattern, the exponent character
immediately followed by one or more
digit characters indicates scientific
notation. Example: “0.###E0” formats
the number 1234 as “1.234E3”.

The more difficult part is how to switch between ordinary notation and scientific notation.
I did this by embedding two decimal formatters in one of the choide formatters in Messageformater :

MessageFormat format = new MessageFormat(
"{0,choice,0#{0,number,'#,##0.####'}|99999<{0,number,'000000.####E0'}}",
                Locale.ENGLISH);

(This example has only 6 decimal places, but you can change it.) )

The usage of message formats is a bit different from decimal formatters because the format method requires an array of objects.

System.out.println(format.format(new Object[] { 123 }));

It prints for (1, 12, 123, …).

1
1.1
12
123
1,234
12,345
123456E0
123456.7E1
123456.78E2
123456.789E3
123456.789E4
123456.789E5
123456.789E6

You’ll need to tweak the mode a bit to make it fit your 20-bit requirements, but the way should be clear.

Even though I’ve proven it works, I recommend implementing your own Formater, which uses 2 decimal formatters and an if condition.

Related Problems and Solutions