Nicholas
Nicholas

Reputation: 5520

How to format 1000000 to 1,000,000 etc

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

Answers (3)

pb2q
pb2q

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

ataylor
ataylor

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

Alex
Alex

Reputation: 25613

Take a look at NumberFormat and DecimalFormat.

new DecimalFormat("#,###,###").format(1000000);

Upvotes: 5

Related Questions