Domanda

I'm trying to have only three numbers after the comma in my double value. I do:

DecimalFormat dfi_ = new DecimalFormat("#.000");

My double :

double myD = 6.082483660549182E-15;
System.out.println("DF Version of myD: " + dfi_.format(myD));

but the result was : DF Version of myD: ,000

Thanks,

È stato utile?

Soluzione

The result is correct. It displays the (localized) number, with a precision of 3 digits after the decimal.

The value 6.082483660549182E-15 is 0.0000000000000060824.., which is very close to 0.

Now, to display the number in Scientific Notation, consider a format of "###.0E0" - this should result in an output of 6,082E-15 (where the decimal is determined by locale), which I believe is desired.

(If the question is just about the comma, then that's merely a localization issue.)

Altri suggerimenti

Try this one. Find out your region (Locale) and use that locale specific DecimalFormat.

For more info have a look at NumberFormat#getNumberInstance(Locale).

    double no = 123456.7890;

    for (Locale locale : Locale.getAvailableLocales()) {
        NumberFormat numberFormat = DecimalFormat.getNumberInstance(locale);

        System.out.println("========================================");
        System.out.println(locale.getDisplayCountry() + " - " + locale.toString());
        System.out.println(numberFormat.format(no));

        DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
        String numberPattern = decimalFormat.toLocalizedPattern();
        System.out.println(numberPattern);
    }

output:

        ========================================
        Malaysia - ms_MY
        123,456.789
        #,##0.###
        ========================================
        Qatar - ar_QA
        123,456.789
        #,##0.###;#,##0.###-
        ========================================
        Iceland - is_IS
        123.456,789
        #.##0,###
        ========================================
        Finland - fi_FI
        123 456,789
        # ##0,###
        ========================================
         - pl
        123 456,789
        # ##0,###
        ========================================
        Malta - en_MT
        123,456.789
        #,##0.###

 and so on...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top