0

Given the example code:

String format = "{0,number}"; // <- What do I put here?
double value = Math.PI * 1e-10;
System.out.println(value);
System.out.println(new MessageFormat(format, Locale.US).format(new Object[]{value}));
System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Object[]{value}));

What do I use as the format string such that I get full precision output of any double value and that the output is localized? For example, the output of the current code is:

3.1415926535897934E-10
0
0

String.valueOf(double) correctly prints the full precision, but it isn't a message format and it is not localized. The message format decides the value is too small to bother with. For large numbers the results are even worse! MessageFormat prints 16 significant digits and then appends a bunch of zeros that do not accurately reflect the value stored in the double. E.g. with pi * 1e100 I get:

3.141592653589793E100
31,415,926,535,897,930,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
31 415 926 535 897 930 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
Evan
  • 538
  • 6
  • 11
  • Perhaps: https://stackoverflow.com/questions/22513607/how-to-get-the-pattern-of-number-format-of-a-specific-locale will be of help. – John M I Davis Dec 19 '18 at 19:10

1 Answers1

0

For your requirement and only for it, this is an easiest solution which fits to your code.

Using # symbol below, we show the digits only when they are not 0, otherwise they are being omit.

double value = Math.PI*1e-10;
        String format = "{0,number,#.###############E0}"; // <- What do I put here?

        System.out.println(value);
        System.out.println(new MessageFormat(format, Locale.US).format(new Double[]{value}));
        System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Double[]{value}));

If you want to omit conversion of formatting numbers using scientific notifications, for example instead of 9.424777960769379E2( if in format #.###############E0) or 94.24777960769379E1 ( if in format ##.###############E0 ) to be 942.4777960769379, just use code below:

        double value = Math.PI*1e-10;
        String format = "{0,number,#.################}"; // <- What do I put here?

Take a look and if there is something you need additionally, feel free to ask!

MS90
  • 1,219
  • 1
  • 8
  • 17
  • you're second example doesn't output full precision. Good point on scientific notation. It's still not as nice as Double.toString() which decides whether to use scientific notation based on the magnitude of the value. – Evan Dec 20 '18 at 21:34