Java formats Numbers into currency string instance code

  • 2020-04-01 02:59:38
  • OfStack

Numbers can mark currency, percentages, points, phone Numbers, etc. In terms of currency, they are 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 the currency format of different countries is used.

Here's the idea: use the NumberFormat class's getCurrencyInstance() method to create different objects with different parameters, and use the format() method on that object, and the method parameter is the number entered by the user.

The code 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 annotated input stream scanner 
        System.out.println(" Please enter a number: ");
        double number
 = scan.nextDouble();//
  Gets the user input number 
        System.out.println(" The number in Locale The following constants of the class are used as construction parameters of the formatting object to obtain different currency formats: ");
        //
  Create a format object 
        NumberFormat
 format = NumberFormat.getCurrencyInstance(Locale.CHINA);
        //
  The output formats the 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 as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201402/2014224150450270.png" >


Related articles: