Question

I have read many threads, and it seems to be the best solution to keep 2 places in my double number:

DecimalFormat df = new DecimalFormat("#.00");
double d = 1.234567;
System.out.println(df.format(d));

But when I use it, it prints:

1,23

I want to keep the DOT, cause I need this format (#.##) to use (I will use it as string). How do I keep this dot?

Was it helpful?

Solution

If you want a dot rather than a comma, you should specify a Locale which uses dot as the decimal separator, e.g.

DecimalFormat df = new DecimalFormat("#.00",
                                    DecimalFormatSymbols.getInstance(Locale.US));

Basically, "." in a format pattern doesn't mean "dot", it means "decimal separator".

OTHER TIPS

Try this one. In this case you don't need to define the pattern.

DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH);
format.setMaximumFractionDigits(2);
System.out.println(format.format(1.234567));

Have a look at this program. Find out your locale and use locale specific NumberFormat.

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class LocaleNumberFormatDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double no = 123456.7890;

        System.out.println(Locale.getAvailableLocales().length);
        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,###

and so on...

Whether a period (.) or comma (,) is shown for a decimal is determined by where you are located, or rather the locale your environment is set to use. Some countries use commas instead of points, so this is expected behavior. You should be able to change your locale in your Decimal Format declaration if you absolutely need a decimal point (.).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top