在 java 中将数字四舍五入到 5 美分
Round a number to 5 cents up in java
我正在尝试找出如何使用此规则对货币进行四舍五入:
Tax calculated | Taxe imputed |
|---------------|--------------|
| 0.99 | 1.00 |
| 1.00 | 1.00 |
| 1.01 | 1.05 |
| 1.02 | 1.05 |
我尝试了各种四舍五入的方法,但总是出现错误:
我有 2 本书,12.49 欧元,含税 10%;
和一张 14.99 欧元的 CD,含税 20%
我试过这个方法,但总是得到错误的结果
double number = 12.49 * 0.1 * 2;
double number2 = 14.99 * 0.2;
double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0;
double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;
控制台打印 5.5 (round1+round2) 但我应该得到 5.53
请帮忙
(double)Math.round(value * 100000d) / 100000d
这是 5 位数的精度。零的数量表示
小数位数。
请看一下 this(堆栈溢出问题)和
this(oracle 文档)
double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0;
double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;
所以,要么你重新考虑括号的位置
(重新排列值)或请使用另一个不带圆角的变量
先做round()操作。
在这种情况下,
double round1 = Math.round(number * 1000.0 /5.0) * 5.0 / 1000.0;
double round2 = Math.round(number2 * 1000.0 /5.0) * 5.0 / 1000.0;
可能会解决问题,但最好是正确执行,所以
它将在以后保持有意义。
使用十进制格式输出字符串,例如,
double val=8.888888;
DecimalFormat df = new DecimalFormat("#.###");//for 3 decimal places
df.setRoundingMode(RoundingMode.CEILING);
String value=df.format(val);
有关更多信息,请查看 Class DecimalFormat,请记住它可以解析为数字,如果确实有必要的话。
我正在尝试找出如何使用此规则对货币进行四舍五入:
Tax calculated | Taxe imputed |
|---------------|--------------|
| 0.99 | 1.00 |
| 1.00 | 1.00 |
| 1.01 | 1.05 |
| 1.02 | 1.05 |
我尝试了各种四舍五入的方法,但总是出现错误:
我有 2 本书,12.49 欧元,含税 10%; 和一张 14.99 欧元的 CD,含税 20%
我试过这个方法,但总是得到错误的结果
double number = 12.49 * 0.1 * 2;
double number2 = 14.99 * 0.2;
double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0;
double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;
控制台打印 5.5 (round1+round2) 但我应该得到 5.53
请帮忙
(double)Math.round(value * 100000d) / 100000d
这是 5 位数的精度。零的数量表示 小数位数。
请看一下 this(堆栈溢出问题)和 this(oracle 文档)
double round1 = Math.round(number * 100.0 /5.0) * 5.0 / 100.0; double round2 = Math.round(number2 * 100.0 /5.0) * 5.0 / 100.0;
所以,要么你重新考虑括号的位置 (重新排列值)或请使用另一个不带圆角的变量 先做round()操作。
在这种情况下,
double round1 = Math.round(number * 1000.0 /5.0) * 5.0 / 1000.0; double round2 = Math.round(number2 * 1000.0 /5.0) * 5.0 / 1000.0;
可能会解决问题,但最好是正确执行,所以 它将在以后保持有意义。
使用十进制格式输出字符串,例如,
double val=8.888888; DecimalFormat df = new DecimalFormat("#.###");//for 3 decimal places df.setRoundingMode(RoundingMode.CEILING); String value=df.format(val);
有关更多信息,请查看 Class DecimalFormat,请记住它可以解析为数字,如果确实有必要的话。