Java Parse String to Number using NumberFormat class
Tags: java.text.NumberFormat Java Parse Number
In this Java tutorial we learn how to convert a String value into Number value using java.text.NumberFormat class.
Table of contents
- How to use java.text.NumberFormat to Parse String to Number
- Parse String to Number with a Specified Locale
How to use java.text.NumberFormat to Parse String to Number
To use the NumberFormat class we need to get the instance of it using the NumberFormat.getInstance() method as the following Java program.
ParseNumberExample1.java
import java.text.NumberFormat;
import java.text.ParseException;
public class ParseNumberExample1 {
public static void main(String... args) throws ParseException {
NumberFormat numberFormat = NumberFormat.getInstance();
Number number = numberFormat.parse("123,456.7");
System.out.println(number);
}
}
123456.7
Parse String to Number with a Specified Locale
NumberFormat also allow to parse a String in a specified Locale format. In order to do that we can get instance of NumberFormat with a given Locale as below.
ParseNumberExample2.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class ParseNumberExample2 {
public static void main(String... args) throws ParseException {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMANY);
Number number = numberFormat.parse("123.456,7");
System.out.println(number);
}
}
123456.7
The following example to show how to get instance of NumberFormat with specified language and country of Locale.
ParseNumberExample3.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class ParseNumberExample3 {
public static void main(String... args) {
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("da", "DK"));
Number number = null;
try {
number = numberFormat.parse("123.456,7");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(number);
}
}
123456.7
Happy Coding 😊