Formatting and Parsing a Number for a Locale


 

Formatting and Parsing a Number for a Locale

In this section, you will learn how to format and parse a number for a Locale.

In this section, you will learn how to format and parse a number for a Locale.

Formatting and Parsing a Number for a Locale

In this section, you will learn how to format and parse a number for a Locale.

Formatting converts a date, time, number, or message from its internal representation into a string. Parsing is just reverse of it. It converts a string into an internal representation of the date, time, number, or message. Java has provide different classes for these purposes. You can format numbers, currencies and percentage according to the specified locale by invoking the methods of these classes. Here we are going to format and parse a number for a locale using the class NumberFormat.

Every country has their own way of number representation, like Canada use 'dot' as their decimal point, Germany use comma as their decimal point etc. In the given example, we have format a number for the locale CANADA. The method getNumberInstance() returns the number format for the specified locale and the method format() formats the number. For parsing, we have used the method parse() which parse the text to produce a number.

Here is the code:

import java.text.*;
import java.util.*;

public class FormattingAndParsingNumberForLocale {
	public static void main(String[] args) {
		Locale locale = Locale.CANADA;
		String st = NumberFormat.getNumberInstance(locale).format(-1234.56);
		System.out.println(st);
		try {
			Number number1 = NumberFormat.getNumberInstance(locale).parse(st);
			System.out.println(number1.doubleValue());
		} catch (ParseException e) {
		}
	}
}

Output:

-1,234.56
-1234.56

Ads