Formatting numbers in a Java / Indian numbering system

I want to get the number in the following format:

1000 = 1,000 10000 = 10,000 100000 = 1,00,000 

I tried this:

 import java.text.DecimalFormat; public class StringProcessingDemo { public static void main(String[] args) { String pattern = "##,##,###.###"; DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(2564484.125); System.out.println(output); } } 

But despite the pattern ##,##,###.### , I get the output as 2,564,484.125 , while I think I should get it as 25,64,484.125 . Why?

0
source share
3 answers

You can achieve your requirement with this

 public static String format(double value) { if(value < 1000) { return format("###", value); } else { double hundreds = value % 1000; int other = (int) (value / 1000); return format(",##", other) + ',' + format("000", hundreds); } } private static String format(String pattern, Object value) { return new DecimalFormat(pattern).format(value); } 
+3
source

But despite the pattern ##, ##, ###. ###, I get the output as 2,564,484.125, while I think I should get it as 25,64,484.125. Why?

You can provide multiple grouping characters, but only one is used. From Javadoc :

If you supply a template with multiple grouping characters, the interval between the last and the end of the integer is the one used .

So "#, ##, ###, ####" == "######, ####" == "##, ####, ####"

It seems that formatting the Lakh format is not possible with standard Java mechanisms, see Formatting numbers in java to use the Lakh format instead of a million formats for the solution.

+2
source

This may be due to the format of the number: million, billion and trillion ... So, I created a java function for your need:

String lakhFormattedComma(Double d){ String[] str=d.toString().split("\\."); int len=str[1].length(); if(str[1].substring(len-3,len-1).equals("E-")) return String.format("%."+(len-3+Integer.valueOf(str[1].substring(len-1)))+"f", d); else if(str[1].substring(len-2,len-1).equals("E")) str=String.format("%."+(len-2-Integer.valueOf(str[1].substring(len-1)))+"f", d).split("\\."); String out="."+str[1]; len=str[0].length(); if(len<3) return str[0]+out; out=str[0].substring(len-3)+out; for(int i=len-5;i>=0;i=i-2){ out=str[0].substring(i,i+2)+","+out; if(i==1) out=str[0].substring(0,1)+","+out; } return out; }

-one
source

All Articles