有没有办法去掉 5 的四舍五入的奇偶规则?

Is there a way to remove the even-odd rule of rounding for 5 and round up?

正在申请订票。对于总计,我将小计、hst 和服务费加在一起,并将总计的总和设置为十进制格式。如果总数是 x.85,则四舍五入为 x.8,但我想要 x.9 有没有办法去除 5 舍入和向上舍入的奇偶规则?

我试过 BigDecimal,但它似乎对我不起作用。

DecimalFormat df = new DecimalFormat("$#,###.00");

grandTotal = subTotal + hst + serviceFees;
System.out.printf("%-40s%11s\n", "TOTAL:", df.format(grandTotal));

我希望输出在有 5 时四舍五入,但它只是根据奇偶规则进行四舍五入。

您使用的是浮点数 (double),它只是实际值的近似值。 尤其是有了清单和总计,你总是很难把所有事情都做对。 您无法控制总数是 2.35(实际上永远不会)还是 2.349999998,后者会向下舍入。

将 BigDecimal 与 String 构造函数一起使用:new BigDecimal("1.20"),具有 2 位小数的小数。

请注意,您必须使用 add/multiply i.o。 +/*.

伙计们,我刚刚将 double 数据类型切换为 float 类型并且它工作了 ayyyyy !!!!!!!

您只需要一位小数。

您当前的代码四舍五入正确,只是小数位数太多。

您要求的舍入模式称为 HALF UP,这是 DecimalFormat 的默认值,也是 printf() 唯一可能的舍入模式。 (如果您不想将零显示为分数,也可以使用格式 $#,###.#。)


因此您可以很好地使用小数格式,甚至 System.out.printf() 但将 小数位数 限制为 1:

DecimalFormat df = new DecimalFormat("$#,###.0"); //set MIN and MAX fraction digits to 1
df.setRoundingMode(RoundingMode.HALF_UP);         //default but showing usage if needed

System.out.println(df.format(123454.84d));
System.out.println(df.format(123454.85d));
System.out.printf("$%,.1f", 123454.85d);          //HALF UP rounding the only option

打印:

3,454.8
3,454.9
3,454.9