如何将数字转换为金钱

时间:2019-10-15 17:34:13

标签: java

我不知道如何将我输入的“希望的钱”转换为数字,然后将其转换为货币格式,您可以在下面的代码中看到它,它会问我我的希望钱,然后我输入数字100000例如,我希望它自己将其转换为货币格式

package com.codewitheli;

import java.text.NumberFormat;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Hello matar, Please Enter your wish money");
        String grade = scanner.nextLine();
        System.out.println("Your name wish money is: " + grade);

2 个答案:

答案 0 :(得分:1)

使用可以使用类似的东西

double amount = scanner.nextDouble()

NumberFormat us     = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat china  = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

System.out.println("US: "     + us.format(amount));
System.out.println("China: "  + china.format(amount));
System.out.println("France: " + france.format(amount));

完整程序:

import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the amount: ");
        double amount = scanner.nextDouble();

        NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US);
        NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA);
        NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE);

        System.out.println("US: " + us.format(amount));
        System.out.println("China: " + china.format(amount));
        System.out.println("France: " + france.format(amount));
    }
}

样品运行:

Enter the amount: 200
US: $200.00
China: ¥200.00
France: 200,00 €

答案 1 :(得分:0)

你的意思是这样吗?

String formatted = NumberFormat.getCurrencyInstance(Locale.US).format(1000000);
System.out.println(formatted); //Prints "$1,000,000.00"


    Scanner scanner = new Scanner(System.in);
    System.out.println("Hello matar, Please Enter your wish money");
    String grade = scanner.nextLine();
    System.out.println("Your name wish money is: " + grade);

要将其集成到代码中,需要将传入的String解析为int:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Hello matar, Please Enter your wish money");
    int grade = scanner.nextInt();
    System.out.println("Your name wish money is: " + NumberFormat.getCurrencyInstance(Locale.US).format(grade));
}