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).
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.
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 ? 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.
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:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With