Formatting and Parsing a Locale-Specific Percentage


 

Formatting and Parsing a Locale-Specific Percentage

In this section, you will learn how to format and parse a locale-specific percentage.

In this section, you will learn how to format and parse a locale-specific percentage.

Formatting and Parsing a Locale-Specific Percentage

In this section, you will learn how to format and parse a locale-specific percentage.

On the basis of customizable patterns, which includes a combination of literal and special characters, we can perform formatting and parsing. Through the use of classes, we can specify any pattern to format the numbers, dates, message etc. Here we are going to format a number into locale specific percentage using NumberFormat class. This class helps in formatting and parsing numbers for any locale.

You can see in the given example, in order to obtain a NumberFormat for a specific locale, we have called NumberFormat's method getPercentInstance(). This method returns a percentage format for the current default locale and the method format() formats the number. For parsing, we have used the parse() method to produce a number.

Here is the code:

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

public class FormattingAndParsingLocaleSpecificPercentage {
	public static void main(String[] args) throws Exception {
		Locale locale = Locale.FRANCE;
		String st = NumberFormat.getPercentInstance(locale).format(123.45);
		System.out.println(st);

		Number number = NumberFormat.getPercentInstance(locale).parse(st);
		System.out.println(number.doubleValue());
	}
}

Output:

12 345 %
123.45

Ads