We often need to format decimal numbers in Java like formatting numbers upto 2 decimal places or 3 decimal places or we want to introduce leading zeros in front of numbers. Thankfully Java programming language provides many different ways to format numbers in Java like either using Math.round() or setScale() from BigDecimal but caveat is that they also do rounding of numbers i.e. 1.6 will be rounded on 2.0 if we use Match.round(). If we are just interested in formatting decimal numbers upto n decimal digits than DecimalFormat is way to go. java.text.DecimalFormat descends from NumberFormat and provides dynamic way of formatting numbers in Java. While creating instance of DecimalFormat you can pass an String pattern which describes on which format decimal number should be formatted and than DecimalFormat.format() method will do the rest for you. In this Java tutorial we will see how to format a decimal number in 2 decimal place, format upto 3 decimal place, using comma to separated 3 digits etc.
Java DecimalFormat Example
DecimalFormat in Java is defined in java.text package and its a subclass of NumberFormat. In order to format a decimal number in Java we need an instance of DecimalFormat with predefined pattern. Once you have instance of DecimalFormat, you can call DecimalFormat.format() method for converting any double or long number into needed format. here is code example of creating DecimalFormat and formatting numbers in Java:
If you look at the output of decimal format example you will see that when we used format upto 2 decimal number any floating point number which has more than 2 digits after decimal point numbers will be printed only up to two digits. same is true in case of formatting numbers upto 3 decimal digit. if decimal number doesn't contain 3 digit than zero will be per pended.
Careful while Formatting Decimal number using DecimalFormatThough java.text.DecimalFormat is a nice utility class and allow you to dynamically format numbers in Java it has one problem that its not thread-safe or synchronized properly. So never share decimal format between multiple threads. Its also not advisable to cache DecimalFormat as static resource without proper synchronization.
That's all on how to format a decimal number in Java using DecimalFormat. There are other way also like I said but DecimalFormat is neat, clean and simple way of formatting numbers upto n number of decimal places.
Other Java Tutorials you may like