Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use DecimalFormat(#.#) with localization

I can use DecimalFormat easily to format my numbers. Example

 DecimalFormat format = new DecimalFormat("#.#");

However, I need to pass this number to be formatted by Localization like this one

        DecimalFormat english = (DecimalFormat)DecimalFormat.getNumberInstance(Locale.ENGLISH);

How to combine the two ? thanks.

like image 436
Bialy Avatar asked Aug 27 '16 16:08

Bialy


1 Answers

You specify the DecimalFormatSymbols to use:

DecimalFormatSymbols symbolsEN_US = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat formatEN_US = new DecimalFormat("#,###.#", symbolsEN_US);
System.out.println(formatEN_US.format(-123456.789)); // prints -123,456.8

DecimalFormatSymbols symbolsDE_DE = DecimalFormatSymbols.getInstance(Locale.GERMANY);
DecimalFormat formatDE_DE = new DecimalFormat("#,###.#", symbolsDE_DE);
System.out.println(formatDE_DE.format(-123456.789)); // prints -123.456,8

DecimalFormatSymbols symbolsFR_FR = DecimalFormatSymbols.getInstance(Locale.FRANCE);
DecimalFormat formatFR_FR = new DecimalFormat("#,###.#", symbolsFR_FR);
System.out.println(formatFR_FR.format(-123456.789)); // prints -123 456,8

DecimalFormatSymbols symbolsIT_CH = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("it-CH"));
DecimalFormat formatIT_CH = new DecimalFormat("#,###.#", symbolsIT_CH);
System.out.println(formatIT_CH.format(-123456.789)); // prints -123'456.8

DecimalFormatSymbols symbolsHI_IN = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("hi-IN"));
DecimalFormat formatHI_IN = new DecimalFormat("#,###.#", symbolsHI_IN);
System.out.println(formatHI_IN.format(-123456.789)); // prints -१२३,४५६.८

DecimalFormatSymbols symbolsTHAI = DecimalFormatSymbols.getInstance(Locale.forLanguageTag("th-TH-u-nu-thai-x-lvariant-TH"));
DecimalFormat formatTHAI = new DecimalFormat("#,###.#", symbolsTHAI);
System.out.println(formatTHAI.format(-123456.789)); // prints -๑๒๓,๔๕๖.๘
like image 145
Andreas Avatar answered Sep 26 '22 00:09

Andreas