How to format Decimal Number in Java - DecimalFormat Example

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.
Read more »

0 Response to "How to format Decimal Number in Java - DecimalFormat Example"

Posting Komentar