【问题标题】:Money format - how do I use it?货币格式 - 我如何使用它?
【发布时间】:2016-02-11 00:51:13
【问题描述】:

我是一名初中生。很难弄清楚如何使用货币格式。我正在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);
 }
}

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

【问题讨论】:

  • 请注意,您应该永远使用浮点数来存储货币。该格式以二进制形式存储数据,因此它表示为一些无符号二进制整数(有效数)* 2 的某个幂。因为它是以 2 而不是 10 的幂存储的,所以你可能会遇到很多麻烦。而是使用定点方法(例如,将美分数存储在long 中)more reading

标签: java currency


【解决方案1】:

将您的 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.text 中有一个 NumberFormat 也有帮助。如果您需要帮助,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 2011-09-16
相关资源
最近更新 更多