我想知道如何将输出格式化为金钱。由于我是Java的初学者,我希望尽可能使用最简单的解决方案,尽管我对所有建议持开放态度。
public static void main(String[] args)
{
int numUnits;
double price;
String item;
Scanner scan = new Scanner(System.in);
// get the data
System.out.println("How many units?");
numUnits = scan.nextInt();
System.out.println("What is the price?");
price = scan.nextDouble();
scan.nextLine();
System.out.println("What is the name of the item?");
item = scan.nextLine();
//calculations
double totalCost = numUnits * price;
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + totalCost);
}
}
答案 0 :(得分:1)
您可以通过多种方式执行此操作,可以使用NumberFormat.getCurrencyInstance()
,这样您就可以根据当前的区域设置属性格式化值...
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + NumberFormat.getCurrencyInstance().format(totalCost));
您还可以通过首先获取对实例的引用来格式化NumberFormat
以满足您的需求...
NumberFormat nf = NumberFormat.getCurrencyInstance();
// Customise format properties...
答案 1 :(得分:0)
double amount =500.0;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
System.out.println(currencyFormatter.format(amount));
您应该使用适合您想要使用的货币的区域设置