8

I have tried using NumberFormat and DecimalFormat. Even though I am using the en-In locale, the numbers are being formatted in Western formats. Is there any option to format a number in lakhs format instead?

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
user2008485
  • 89
  • 1
  • 2

3 Answers3

10

Since it is impossible with standard the Java formatters, 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;
}

output

1,23,456.00
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
7

While the standard Java number formatter can't 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
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
2

This kind of formatting is not possible to do with DecimalFormat. It only allows a fixed number of digits between the grouping separator.

From the documentation:

The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".

If you want to get Lakhs format, you have to write some custom code.

Aleksander Blomskøld
  • 18,374
  • 9
  • 76
  • 82