185

What is the best way to format the following number that is given to me as a String?

String number = "1000500000.574" //assume my value will always be a String

I want this to be a String with the value: 1,000,500,000.57

How can I format it as such?

0

11 Answers 11

297

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));
5
  • can you show an example of how I can use NumberFormat with this particular case? Sep 8, 2010 at 23:45
  • 1
    you can also use below solution - public static String getRoundOffValue(double value){ DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00"); return df.format(value); } May 28, 2014 at 10:48
  • 1
    I also prefer the zero before the point like DecimalFormat formatter = new DecimalFormat("#,##0.00"); - getting .00 for zero sounds wrong for me
    – Leo
    May 10, 2018 at 18:25
  • Just note that instantiating DecimalFormat directly goes against the Javadoc: "In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat." Seems bad design to me but it is what it is.
    – jhyot
    Nov 30, 2022 at 16:18
  • Can it be done for any other character than comma, say '.
    – Mandroid
    Apr 4 at 6:14
69

This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.

    String number = "1000500000.574";
    Double numParsed = Double.parseDouble(number);

    System.out.println(String.format("The input number is: %,.2f", numParsed));
    // Or
    String numString = String.format("%,.2f", numParsed);

For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.

For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

0
60

Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.

String.format("%,d", 2000000)

outputs:

2,000,000
1
  • 1
    also works for floats, e.g., printf("%,f\n",decimalNumber)
    – philwalk
    Dec 31, 2019 at 21:10
50

Once you've converted your String to a number, you can use

// format the number for the default locale
NumberFormat.getInstance().format(num)

or

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
2
  • How to both specify locale and round to (say) 2 decimals?
    – Jonik
    Feb 10, 2014 at 22:30
  • 6
    Ah, never mind, found it: new DecimalFormat("0.##", DecimalFormatSymbols.getInstance(locale))
    – Jonik
    Feb 10, 2014 at 22:39
13

I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)

It supports:

  • Comma Formatting E.g. 1234567 becomes 1,234,567.
  • Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
  • Precision of 0 through 15.
  • Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
  • Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).

The code can be found here. You call it like this:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.

4
  • 2
    This is good if you're working in only English language. My suggestion is to avoid such a thing as it pissed dinner of my non English users as they couldn't understand what K or M means Mar 29, 2015 at 7:35
  • @rishabhmhjn but... couldnt you just tweak it to modify to any letter you need? is your bad luck his fault ? :o and what he created is quite cool, despite the link seems unavailable right now.. May 18, 2017 at 15:38
  • @AquariusPower the problem is, eg., Japanese numbers do not follow the metric system. Their numbers are like 1百 for 100, 1千 for 1000, 1万 for 10000, then it becomes 1千万 for 1000,0000. My team was working on something similar in Javascript. You can use the logic mentioned in this one: github.com/statusbrew/angular-bignumber Jun 28, 2017 at 9:13
  • Found my old code for this so I reuploaded it to GitHub. The Link in comment has been updated. Jan 6, 2019 at 20:17
7

you can also use the below solution

public static String getRoundOffValue(double value){
    DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
    return df.format(value);
}
6
public void convert(int s)
{
    System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}

public static void main(String args[])
{
    LocalEx n=new LocalEx();
    n.convert(10000);
}
4

You can do the entire conversion in one line, using the following code:

String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));

The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.

4

Here is the simplest way to get there:

String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result)); 

output: 10,987,655.88

0
3

The first answer works very well, but for ZERO / 0 it will format as .00

Hence the format #,##0.00 is working well for me. Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.

-2

According to chartGPT

Using DecimalFormat:

DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);

Using NumberFormat:

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);

Using String.format():

String formattedNumber = String.format("%,.2f", yourNumber);

Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.