3

How do you convert number values to include dots or commas in Java? I tried searching the web, but I didn't find a good answer. Anyone got a solution for this?

Nicholas
  • 5,090
  • 2
  • 20
  • 21
  • possible duplicate of [How can I format a String number to have commas and round?](http://stackoverflow.com/questions/3672731/how-can-i-format-a-string-number-to-have-commas-and-round) – Xaerxess Sep 13 '12 at 18:43
  • Look at this answer. http://stackoverflow.com/questions/1097332/convert-a-string-to-number-java – Arvin Am Sep 13 '12 at 18:44

3 Answers3

7

The java.text.NumberFormat class will do this, using the appropriate separator for your locale. Example:

import java.text.NumberFormat;

System.out.println(NumberFormat.getInstance().format(1000000));

==>1,000,000
ataylor
  • 62,796
  • 20
  • 153
  • 185
  • Thanks, helped me out :) I already found the number forma thingy, but I didn't know how to use it because I'm new to java :) – Nicholas Sep 13 '12 at 18:50
6

There's a class called NumberFormat which will handle printing numbers in a certain format and also parsing a String representing a number into an actual Number.

DecimalFormat is a concrete subclass of NumberFormat, you can use DecimalFormat to e.g. format numbers using comma as a grouping separator:

NumberFormat myFormat = new DecimalFormat("#,###");

You can also use DecimalFormat for currency formatting.

Similarly, DateFormat handles parsing and printing dates.

The javadocs are here: NumberFormat, DecimalFormat.

pb2q
  • 56,563
  • 18
  • 143
  • 144
5

Take a look at NumberFormat and DecimalFormat.

new DecimalFormat("#,###,###").format(1000000);
Alex
  • 24,385
  • 6
  • 56
  • 53
  • You only need `"#,###"`. This will set it up to automatically group everything in 3's. +1 for giving a working format string. – Brian Sep 13 '12 at 18:59