Numbers can mark currency, percentages, points, phone numbers, etc. As far as currency is concerned, it will be defined in different formats in different countries. This example will receive the number entered by the user and then output its currency format in the console, where it is used Currency formats in different countries.
The idea is as follows: Use the getCurrencyInstance() method of the NumberFormat class to create different objects through different parameters, and use the format() method for the object. The method parameters are the numbers entered by the user.
The code is as follows:
The code copy is as follows:
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class FormatNumber
{
public static void main(String[]
args) {
Scanner
scan = new Scanner(System.in);//
Create an annotation input stream scanner
System.out.println("Please enter a number:");
double number
= scan.nextDouble();//
Get user input numbers
System.out.println("This number uses the following constants of the Locale class as the construction parameters of the format object, and will obtain a different currency format:");
//
Create a formatted object
NumberFormat
format = NumberFormat.getCurrencyInstance(Locale.CHINA);
//
Output format currency format
System.out.println("Locale.CHINA:" +
format.format(number));
format
= NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("Locale.US:" +
format.format(number));
format
= NumberFormat.getCurrencyInstance(Locale.ENGLISH);
System.out.println("Locale.ENGLISH:" +
format.format(number));
format
= NumberFormat.getCurrencyInstance(Locale.TAIWAN);
System.out.println("Locale.TAIWAN:" +
format.format(number));
}
}
The effect is shown in the picture: