Formatting numbers in java to use the Lakh format instead of a million formats

I tried using NumberFormat and DecimalFormat . Despite the fact that I use the language standard en-In , the numbers are formatted in Western formats. Is there a way to format a number in lakhs format?

Ex - I want NumberFormatInstance.format(123456) to give 1,23,456.00 instead of 123,456.00 (for example, using the system described on this page on Wikipedia ).

+7
source share
3 answers

Since it is not possible with standard Java formatter, I can offer a custom formatter

 public static void main(String[] args) throws Exception { System.out.println(formatLakh(123456.00)); } private static String formatLakh(double d) { String s = String.format(Locale.UK, "%1.2f", Math.abs(d)); s = s.replaceAll("(.+)(...\\...)", "$1,$2"); while (s.matches("\\d{3,},.+")) { s = s.replaceAll("(\\d+)(\\d{2},.+)", "$1,$2"); } return d < 0 ? ("-" + s) : s; } 

Exit

 1,23,456.00 
+8
source

While the standard Java number formatter cannot handle this format, the DecimalFormat class in ICU4J can.

 import com.ibm.icu.text.DecimalFormat; DecimalFormat f = new DecimalFormat("#,##,##0.00"); System.out.println(f.format(1234567)); // prints 12,34,567.00 
+6
source

This kind of formatting cannot be done with DecimalFormat . It allows only a fixed number of digits between the grouping delimiter.

From the documentation :

Group size is a constant number of digits between a group of characters, such as 3 for 100,000,000 or 4 for 1,000,000.00. if you provide a pattern with several grouping characters, the interval between the last and the end of the integer is the one that is equal to that used. So, "#, ##, ###, ####" == "######, ####" == "##, ####, ####".

If you want to get the Lakhs format, you need to write some kind of custom code.

+2
source

All Articles