Sample code to display numbers in different pattern with locale like en_US
Output:
Reference:
https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
package com.kishore.samples; import java.util.*; import java.text.*; public class DecimalFormatDemo { static public void customFormat(String pattern, double value ) { DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " ===> " + pattern + " ===> " + output); } static public void localizedFormat(String pattern, double value, Locale loc ) { NumberFormat nf = NumberFormat.getNumberInstance(loc); DecimalFormat df = (DecimalFormat)nf; df.applyPattern(pattern); String output = df.format(value); System.out.println(pattern + " ===> " + output + " ===> " + loc.toString()); } static public void main(String[] args) { System.out.println("Number formats without Locale"); customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); customFormat("\u00a5###,###.###", 12345.67); Locale currentLocale = new Locale("en", "US"); DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale); unusualSymbols.setDecimalSeparator('|'); unusualSymbols.setGroupingSeparator('^'); String strange = "#,##0.###"; DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); weirdFormatter.setGroupingSize(4); String bizarre = weirdFormatter.format(12345.678); System.out.println(bizarre); Locale[] locales = { new Locale("en", "US"), new Locale("de", "DE"), new Locale("fr", "FR") }; System.out.println("Number formats with Locale"); for (int i = 0; i < locales.length; i++) { localizedFormat("###,###.###", 123456.789, locales[i]); } } }
Output:
Number formats without Locale 123456.789 ===> ###,###.### ===> 123,456.789 123456.789 ===> ###.## ===> 123456.79 123.78 ===> 000000.000 ===> 000123.780 12345.67 ===> $###,###.### ===> $12,345.67 12345.67 ===> ¥###,###.### ===> ¥12,345.67 1^2345|678 Number formats with Locale ###,###.### ===> 123,456.789 ===> en_US ###,###.### ===> 123.456,789 ===> de_DE ###,###.### ===> 123 456,789 ===> fr_FR
Reference:
https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
No comments :
Post a Comment