user2008485
user2008485

Reputation: 89

Number formatting in java to use Lakh format instead of million format

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).

Upvotes: 8

Views: 4971

Answers (3)

Ian Roberts
Ian Roberts

Reputation: 122394

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

Upvotes: 7

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

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

Upvotes: 10

Aleksander Blomsk&#248;ld
Aleksander Blomsk&#248;ld

Reputation: 18552

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.

Upvotes: 2

Related Questions