gpt4 book ai didi

java - 货币格式 - 我如何使用它?

转载 作者:行者123 更新时间:2023-11-30 03:03:42 25 4
gpt4 key购买 nike

我是一名高中三年级学生。很难弄清楚如何使用货币格式。我正在《Java 编程指南》(第二版)中做一个练习,其中我必须提示员工汉堡、薯条和苏打水的数量。

薯条 1.09 美元,汉堡 1.69 美元,苏打水 0.99 美元。

这是我的代码:

import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {

public static void main(String[]args) {

final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;

Scanner input = new Scanner(System.in);


System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();



totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;


System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}

我只想使用货币格式,但我不知道如何使用。我确信这是一个愚蠢的问题,但感谢您的帮助!

最佳答案

将 println 更改为这些,看看是否有帮助:

System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);

还有这个:

NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);

System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);

输出:

Your total before tax is: $8.53 
Tax: $0.55
Your final total is: $9.08
Your change is: $10.92

关于java - 货币格式 - 我如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35328918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com