NumberFormat Class in Java Explained [Practical Examples]


JAVA

NumberFormat Class in Java

The format of currencies in different countries around the world varies widely. They also follow different number systems to represent the numbers. In Java, NumberFormat is the abstract base class present in java.text package that is used to represent numbers in all number formats. This class provides the interface for formatting and parsing numbers. The methods of NumberFormat can also determine the number formats followed by different countries/locales. That means, you can format and parse numbers for any countries. Your code can be completely independent of the country conventions for decimal points, thousands-separators, or even the particular decimal digits used. Apart from this, it also allows us to round the values and set the minimum fraction digits if needed.

Some of the task performed by the NumberFormat class is as listed below:

  • Formatting Numbers
  • Setting number of Digits in Fraction part
  • Rounding Numbers
  • Formatting Percentage
  • Formatting Currency

 

Creating Java NumberFormat

In order to work with NumberFormat first step is to create an instance for a particular locale/country. The statement given below shows the syntax to create an instance.

NumberFormat.getInstance(Locale)

 

Formatting Numbers Using NumberFormat Class

The format of numbers varies according to the locale. For example, USA, Switzerland, Japan use dot(.) as a decimal separator. Whereas some other countries like France, Slovakia, India use comma(,) as a decimal separator.
For thousands-separators USA, Switzerland, Japan use comma(,) whereas India use dot(.) and Slovakia use space( ).

Example : The example below demonstrates the formatting of numbers according to locale using NumberFormat class in Java.

// Importing Packages
import java.util.*;
import java.text.*;
public class Main {
    public static void main(String[] args) {
        double n = 225.813522;
        long x = 778552639;
        // Syntax of Locale(String language, String country)
        System.out.println("Formatting numbers according to different countries in the world");
        NumberFormat nf = NumberFormat.getInstance(new Locale("ch", "Switzerland"));

        // Using format function to format the numbers
        System.out.println("Decimal separator Switzerland : " + nf.format(n));
        System.out.println("Thousands separator Switzerland : " + nf.format(x));

        nf = NumberFormat.getInstance(new Locale("in", "India"));
        System.out.println("\nDecimal separator India : " + nf.format(n));
        System.out.println("Thousands separator India : " + nf.format(x));

        nf = NumberFormat.getInstance(new Locale("jp", "JAPAN"));
        System.out.println("\nDecimal separator Japan : " + nf.format(n));
        System.out.println("Thousands separator Japan : " + nf.format(x));

        nf = NumberFormat.getInstance(new Locale("US", "United States"));
        System.out.println("\nDecimal separator United States : " + nf.format(n));
        System.out.println("Thousands separator United States : " + nf.format(x));

        nf = NumberFormat.getInstance(new Locale("sk", "Slovakia"));
        System.out.println("\nDecimal separator Slovakia : " + nf.format(n));
        System.out.println("Thousands separator Slovakia : " + nf.format(x));
    }
}

Output

Formatting numbers according to different countries in the world

Decimal separator Switzerland : 225.814
Thousands separator Switzerland : 778,552,639

Decimal separator India : 225,814
Thousands separator India : 778.552.639 

Decimal separator Japan : 225.814 
Thousands separator Japan : 778,552,639

Decimal separator United States : 225.814 
Thousands separator United States : 778,552,639

Decimal separator Slovakia : 225,814 
Thousands separator Slovakia : 778 552 639

 

Setting number of digits in the Fraction part using NumberFormat class

We can set number of digits allowed in the fraction portion of a number using NumberFormat class in Java. We can specify the maximum number and minimum number of digits allowed in the fraction portion of a number using setMaximumFractionDigits and setMinimumFractionDigits respectively.

Example : The example below demonstrates the setting number of digit in fraction part using NumberFormat class in Java.

//Importing Packages
import java.util.*;
import java.text.NumberFormat;
public class Main {
    public static void main(String[] args) {
        double n = 225.81352229;
        double x = 778.5;
        NumberFormat nf = NumberFormat.getInstance(new Locale("ch", "Switzerland"));

        // Setting maximum and minimum fraction digits
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(6);
        System.out.println("Minimum fraction digit set for " + x + " is  2. Result is " + nf.format(x));
        System.out.println("\nMaximum fraction digit set for " + n + " is 6. Result is " + nf.format(n));
    }
}

Output

Minimum fraction digit set for 778.5 is 2. Result is 778.50
Maximum fraction digit set for 225.81352229 is 6. Result is 225.813522

 

Rounding Numbers Using NumberFormat Class

In NumberFormat class, if we set maximum fraction digit, it automatically rounds up after the given number of digits. But, In some case we may need to round down the number. So, NumberFormat class provides the function setRoundingMode which can take enum constants like RoundingMode.UP, RoundingMode.DOWN to round up and down the values respectively.

Example : The example below demonstrates the setting number of digit in fraction part using NumberFormat class in Java.

// Importing packages
import java.util.*;
import java.text.NumberFormat;
import java.math.RoundingMode;
public class Main {
    public static void main(String[] args) {
        double n = 225.81352229;

        NumberFormat nf = NumberFormat.getInstance(new Locale("ch", "Switzerland"));

        // Setting rounding mode and maximum fraction digits
        nf.setMaximumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.UP);
        System.out.println("\nRounding up this number  " + n + " to 2 digits. Result is " + nf.format(n));

        // Setting rounding mode and maximum fraction digits
        nf.setRoundingMode(RoundingMode.DOWN);
        System.out.println("\nRounding Down this number  " + n + " to 2 digits. Result is " + nf.format(n));
    }
}

Output

Rounding up this number 225.81352229 to 2 digits. Result is 225.82
Rounding Down this number 225.81352229 to 2 digits. Result is 225.81

 

Formatting Percentage Using NumberFormat Class

The format of Percentage varies according to the locale. We can do this by using the NumberFormat.getPercentInstance to format percentages.

Example : The example below demonstrates the formatting of percentage according to locale using NumberFormat class in Java.

// Importing Package
import java.util.*;
import java.text.NumberFormat;
public class Main {
    public static void main(String[] args) {
        double n = 0.8865 f;

        // Using getPercentInstance method
        NumberFormat nf = NumberFormat.getPercentInstance(new Locale("ch", "Switzerland"));
        System.out.println("\nPercent Format Switzerland : " + nf.format(n));

        nf = NumberFormat.getPercentInstance(new Locale("in", "India"));
        System.out.println("\nPercent Format India : " + nf.format(n));

        nf = NumberFormat.getPercentInstance(new Locale("jp", "JAPAN"));
        System.out.println("\nPercent Format Japan : " + nf.format(n));

        nf = NumberFormat.getPercentInstance(new Locale("US", "United States"));
        System.out.println("\nPercent Format United States : " + nf.format(n));

        nf = NumberFormat.getPercentInstance(new Locale("sk", "Slovakia"));
        System.out.println("\nPercent Format Slovakia : " + nf.format(n));

    }
}

Output

Percent Format Switzerland : 89% 
Percent Format India : 89% 
Percent Format Japan : 89% 
Percent Format United States : 89%
Percent Format Slovakia : 89 %

 

Formatting Currency Using NumberFormat Class

As we know, different countries have different currencies, formatting the currency is the most complex task. We can use the NumberFormat.getCurrencyInstance to get the number format for the currencies.

Example : The example below demonstrates the formatting of percentage according to locale using NumberFormat class in Java.

// Importing packages
import java.util.*;
import java.text.NumberFormat;
public class Main {
    public static void main(String[] args) {
        float n = 55.25 f;

        // Using getCurrencyInstance method
        NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
        System.out.println("United States " + (nf.format(n)));

        nf = NumberFormat.getCurrencyInstance(new Locale("hr", "HR"));
        System.out.println("Croatia " + nf.format(n));

        nf = NumberFormat.getCurrencyInstance(new Locale("zh", "CN"));
        System.out.println("China " + nf.format(n));

        nf = NumberFormat.getCurrencyInstance(new Locale("in", "IN"));
        System.out.println("India " + nf.format(n));

        nf = NumberFormat.getCurrencyInstance(new Locale("ch", "CH"));
        System.out.println("Switzerland " + nf.format(n));
    }
}

Output

United States $55.25
Croatia 55,25 HRK
China ï¿¥55.25
India Rs55,25
Switzerland CHF 55.25

 

Summary

The knowledge of NumberFormat class of java.text package is very important for a Java developer to know while developing an application that will be used worldwide. In this tutorial, we covered the methods of NumberFormat class that can be used to format the data according to their locale. We learned in detail about the usage of some important methods along with example. All in all, this tutorial, covers everything that you need to know in order to understand the NumberFormat class in Java and select an appropriate method for formatting the numbers in the application.

 

References

NumberFormat class in Java
Country/Region codes used by Locale

 

Deepak Prasad

Deepak Prasad

Deepak Prasad is the founder of GoLinuxCloud, bringing over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, Networking, and Security. His extensive experience spans development, DevOps, networking, and security, ensuring robust and efficient solutions for diverse projects.

Certifications and Credentials:

  • Certified Kubernetes Application Developer (CKAD)
  • Go Developer Certification
  • Linux Foundation Certified System Administrator (LFCS)
  • Certified Ethical Hacker (CEH)
  • Python Institute PCAP (Certified Associate in Python Programming)
You can connect with him on his LinkedIn profile and join his Facebook and LinkedIn page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

1 thought on “NumberFormat Class in Java Explained [Practical Examples]”

  1. This had me confused. You’re doing something weird.

    new Locale(“in”, “India”) does not create a “locale for India”, it creates a locale for _Indonesian_ (language code “in”) in a free-text country called “INDIA”. The extra confusing stuff is that “in” is not the standard ISO language code for Indonesian macro language, it’s “id”, but apparently “in” still works.

    Reply

Leave a Comment