Use DecimalFormat(#.#) with localization
Asked Answered
K

2

6

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.

Kindless answered 27/8, 2016 at 16:42 Comment(0)
R
12

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 -๑๒๓,๔๕๖.๘
Rostock answered 27/8, 2016 at 17:14 Comment(1)
nice solution :)Kindless
K
-1

Found the answer here : https://www.iro.umontreal.ca/~vaucher/Java/tutorials/Formatting.html

just Locale.setDefault(Locale.ENGLISH); before DecimalFormat object

Locale.setDefault(Locale.ENGLISH);
DecimalFormat format = new DecimalFormat("#.#");
Kindless answered 27/8, 2016 at 17:6 Comment(1)
That won't work if you need multiple Locales in a multi-threaded application.Rostock

© 2022 - 2024 — McMap. All rights reserved.