Java NumberFormat getInstance Method



In this article, we will learn how to format numbers in Java using the NumberFormat class from the java.text package. The NumberFormat class provides methods for formatting numbers based on Locale settings, which is useful for creating internationalized Java applications. Using the NumberFormat.getInstance() method, we can format double, int, or float values in a Java program. 

Problem Statement

Given a decimal value, we need to format the number using Java's NumberFormat class to round it according to the default Locale settings.
Input
double val = 1.9898798;

Output

Formatted Value: 1.99

Steps to format numbers using NumberFormat

The following are the steps to format numbers using NumberFormat

  • Import the NumberFormat class from the java.text package.
  • Use the NumberFormat.getInstance() method to get an instance of the NumberFormat class.
  • Declare and initialize a double value.
  • Use the format() method of the NumberFormat instance to format the double value.
  • Print both the original value and the formatted result.

Java program to format numbers using NumberFormat

The following is an example to format numbers using NumberFormat.

import java.text.NumberFormat;
public class Demo {
public static void main(String args[]) {
 NumberFormat n = NumberFormat.getInstance();
 double val = 1.9898798;
 System.out.println("Value: "+val);
 String formattedVal = n.format(val);
 System.out.println("Formatted Value: "+formattedVal);
}
}

Output

Value: 1.9898798
Formatted Value: 1.99

Code Explanation

In this Java program, we import NumberFormat from the java.text package. In the main method, we use NumberFormat.getInstance() to get an instance of the NumberFormat class, which adapts the formatting rules to the default Locale. We then declare a double variable val and initialize it with the value 1.9898798. Using the format() method of the NumberFormat instance, we format the decimal number and round it to two decimal places based on the Locale-specific settings. In the end both the original and formatted values are printed.

Updated on: 2024-11-04T18:41:47+05:30

519 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements