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?
Asked
Active
Viewed 5,209 times
3
-
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) – Grzegorz Rożniecki 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 Answers
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
- 64,891
- 24
- 161
- 189
-
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
- 58,613
- 19
- 146
- 147
5
Take a look at NumberFormat and DecimalFormat.
new DecimalFormat("#,###,###").format(1000000);

Alex
- 25,147
- 6
- 59
- 55
-
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