Formatting Numbers using NumberFormat Class

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Filament.io 0 Flares ×

Java provides good support for formatting numbers in any way you want. You may want to display numbers in different formats based on the country or region. You may also need to display in a different format based on the user preferences. The use cases are many. Let us see how we can use the NumberFormat class of java.text.* package. to accomplish this.

Java has the java.text.* package packed with formatting routines. The java.text package includes a Locale class and this is helpful in formatting numbers based different Locale settings. The NumberFormat class provides a factory method called getInstance() that returns a DecimalFormat based on the default locale of the users virtual machine.

The two variations of the factory method are

  1. public static final NumberFormat getInstance() – Returns a general-purpose number format for the current default locale.
  2. public static NumberFormat getInstance(Locale inLocale) – Returns a general-purpose number format for the specified locale.

This calss also provides the method setMinimumIntegerDigits , setMinimumFractionDigits and setMaximumFractionDigits to format the numbers as per the needs. For example setting setMinimumIntegerDigits(3) ensures that you will always get the number formatted as 3 digits ( For example 004)

NumberFormat – Example

Output

004.00
120.5689

If you want to dynamically change the format, you can use the applyPattern(). Here is an example for this

DecimalFormat – Change Format Dynamically – Example

Output

004.00
120.5689
120.57

DecimalFormat – Patterns


# Numeric digit, zero shows as absent
0 Numeric digit
. Locale-specific decimal separator (decimal point)
, Locale-specific grouping separator (comma in English)
– Locale-specific negative indicator (minus sign)
% Shows the value as a percentage
; Separates two formats: the first for positive and the second for negative values
‘ Escapes one of the above characters so it appears