Reputation: 5520
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?
Upvotes: 3
Views: 5757
Reputation: 59667
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
.
Upvotes: 6
Reputation: 66109
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
Upvotes: 7
Reputation: 25613
Take a look at NumberFormat and DecimalFormat.
new DecimalFormat("#,###,###").format(1000000);
Upvotes: 5