java - 我将如何做到这一点,以便输出将四舍五入到小数点后两位?
问题描述
我的代码在这里运行良好,但是每当我运行它时,它似乎并没有四舍五入,我不知道要添加什么以及在哪里添加它。
package com.mycompany.billofsale;
public class Billofsale {
public static void main(String[] args) {
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
System.out.println("The total is "+s
+ "\n The tax is "+result
+ "\n The total cost with tax is "+result2
+ "\n The change is "+result3);
}
}
解决方案
您需要使用 DecimalFormat 将要打印的所有数字格式化为所需的小数。
试试这个代码:
double s = 12.49;
double p = 20.00;
double t = 0.13;
double result = s * t;
double result2 = s + result;
double result3 = p - (s + result);
DecimalFormat format = new DecimalFormat(".00");
format.setRoundingMode(RoundingMode.HALF_UP);
System.out.println("The total is " + s + "\n The tax is " +format.format(result) + "\n The total cost with tax is " + format.format(result2)
+ "\n The change is " + format.format(result3));
推荐阅读
- sorting - 如何在 prolog 中编写 gnom 排序?
- sql - 如何在 SQL Server 中同时独立运行多个简单的 select 语句?
- c++ - 程序使用复制构造函数而不是移动构造函数
- php - 如何在 laravel 7 中更新或创建多个组?
- java - Android SDK 组件中的 SDK 工具和构建工具有什么区别?
- rest - 从 SP 2013 迁移到 SPO 日期时间问题
- javascript - javascript搜索没有效果
- javascript - 我可以在烧瓶中返回两个 ByteArray 吗?
- html - 滚动条重组网页文本
- python - 网页抓取 & BeautifulSoup
- 解析