Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 564
user2008485 Avatar asked Jan 24 '13 17:01

user2008485


People also ask

How to format numbers in Java?

In this tutorial, we'll look at different approaches to number formatting in Java and how to implement them. 2. Basic Number Formatting with String#format The String#format method is very useful for formatting numbers. The method takes two arguments.

What are the methods of numberformat class?

It is the abstract base class for all number formats. Following are some of the methods of the NumberFormat class− Overrides Cloneable. Overrides equals. String.

What's new in numberformat?

What's New ? NumberFormat is an abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales (US, India, Italy, etc.) have number formats and their names. NumberFormat helps you to format and parse numbers for any locale.

What is the first argument in decimal formatting in Java?

The first argument describes the pattern on how many decimals places we want to see, and the second argument is the given value: 3. Decimal Formatting by Rounding In Java, we have two primitive types that represent decimal numbers – float and decimal:


2 Answers

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
like image 121
Evgeniy Dorofeev Avatar answered Sep 19 '22 03:09

Evgeniy Dorofeev


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
like image 22
Ian Roberts Avatar answered Sep 22 '22 03:09

Ian Roberts