在Java中如何将价格显示为保留两位小数(精确到分)的格式?
问题原因
你代码的问题出在最终总价格的输出逻辑:System.out.printf("Total Price: $"+total); 直接对字符串做了拼接,没有使用printf的格式化占位符,因此无法触发保留两位小数的格式化规则。
解决方案
方案1:直接修正printf语法(最快修复)
把最后一行输出总价格的代码替换为:
System.out.printf("Total Price: $%.2f%n", total);
其中%.2f是浮点型保留两位小数的格式化占位符,默认会对第三位小数做四舍五入处理,符合金额精确到分的需求;%n是跨平台适配的换行符,代替硬编码的\n。
方案2:使用String.format格式化后输出
和你代码中已有的测试格式化逻辑一致,先把总价格格式化为指定字符串再输出:
String totalFormatStr = String.format("Total Price: $%.2f", total); System.out.println(totalFormatStr);
方案3:金额场景更推荐的BigDecimal方案(避免浮点精度丢失)
double属于浮点型,存储金额时容易出现精度丢失问题(比如0.1+0.2不等于0.3的经典问题),涉及金额计算更推荐用BigDecimal处理,示例实现如下:
// 定义价格时改用BigDecimal BigDecimal apptPrice = BigDecimal.ZERO; BigDecimal entreePrice = BigDecimal.ZERO; BigDecimal dessertPrice = BigDecimal.ZERO; // 读取价格时转换为BigDecimal BigDecimal price = new BigDecimal(item[1].substring(1)); // 求和逻辑 BigDecimal total = apptPrice.add(entreePrice).add(dessertPrice); // 格式化输出,保留两位小数 System.out.printf("Total Price: $%.2f%n", total);
修正后可直接运行的完整代码
import java.io.*; import java.util.*; public class Menu { public static void main(String[] args){ String apptName = ""; String entreeName = ""; String dessertName = ""; double apptPrice = 0.00; double entreePrice = 0.00; double dessertPrice = 0.00; try { Scanner sc = new Scanner(new File("menu.txt")); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] item = line.split(", "); int type = Integer.parseInt(item[2]); String name = item[0]; double price = Double.parseDouble(item[1].substring(1)); if (type == 1) { if (price > apptPrice) { apptName = name; apptPrice = price; } } else if (type == 2) { if (price > entreePrice) { entreeName = name; entreePrice = price; } } else { if (price > dessertPrice) { dessertName = name; dessertPrice = price; } } } double total = apptPrice + entreePrice + dessertPrice; System.out.println("Please enter the filename you wish to process: Most Expensive Meal"); System.out.println("-------------------"); System.out.println("Appetizer : "+apptName); System.out.println("Entree : "+entreeName); System.out.println("Dessert : "+dessertName); // 修正后的输出语句 System.out.printf("Total Price: $%.2f%n", total); } catch (FileNotFoundException fe) { System.out.println("Sorry, input file: was not found."); } } }
内容的提问来源于stack exchange,提问作者user17608411
相关产品推荐
相关产品推荐

