Java DecimalFormat example

Previous
Next

In this post, we will see how to format a number using DecimalFormat in java.

DecimalFormat

DecimalFormat class is subclass of NumberFormat class and it is used to format numbers by using specify formatting pattern.We can format a number upto 2 decimal place,upto 3 decimal place, using comma to separate digits.

Creating DecimalFormat object

The string(i.e  pattern) we pass in DecimalFormat constructor specify format for the number.

DecimalFormat’s format method can be used to format a number.Once we create object of DecimalFormat object, we can call format method and pass the number as parameter.

Few  Number Format pattern are:

Symbol Meaning
0 It always displayed 0,if number has less digit
# A digit,leading zeros are ommitted and displayed fixed digit
. Marks decimal separator.
, Marks grouping separator.

Below examples will help you understand better.

Pattern Number Formatted String
00.## 8.567  08.56
###,###.## 987654.56 987654.56
###.000 12345.84 12345.84


Below example shows the use of DecimalFormat in java:- 

Output

987,675,341.90
7,654,341.99
1,000,000,980.000
10,000,000.980
10,000,000.987

In our above example, when we format upto 2 decimal place then number having more than two digits after decimal will print only two digits and in upto 3 decimal place will print upto only 3 digits if less than three digits are there than it will placed zero in the end.

Grouping the digits

You can group the digits starting from decimal by using method setGroupSize() on DecimalFormat object.

When you run above program, you will get below output

9,8765,4341.90

Please note that DecimalFormat is not thread safe means in multithreading environment don’t use DecimaFormat.

That’s all about DecimalFormat in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog