简体   繁体   English

Java decimalFormat RoundingMode

[英]Java decimalFormat RoundingMode

I need to archive this: (basically num1 * num2 = num3 and num1 and num2 are given) 我需要对此进行存档:(基本上是num1 * num2 = num3并给出了num1num2

1) 10.62 * 4.0 = 42.48 
2) 14.89 * 8.5 = 126.56 
3) 13.21 * 6.0 = 79.26 
4) 16.55 * 7.35 = 121.64 
5) 18.62 * 9.0 = 167.58 
6) 9.47 * 15.3 = 144.89
7) 6.58 * 3.0 = 19.74 
8) 18.32 * 5.4 = 98.93 
9) 12.15 * 2.9 = 35.24 
10) 3.98 * 4.8 = 19.10

This exercise is to practice formatting/rounding string/number. 本练习是练习格式化/舍入字符串/数字。

So I used: 所以我用了:

DecimalFormat decimalFormat = new DecimalFormat(".00");
System.out.println(decimalFormat.format(num3));

and got everything right but the 9) 12.15 * 2.9 = 35.24 , I got 35.23 instead of 35.24 The default RoundingMode of DecimalFormat is HALF_EVEN, if I use RoundingMode.UP I will get this right 35.24 but the others results will be messed so I am stuck... 并得到正确的结果,但9) 12.15 * 2.9 = 35.24 ,我得到的是35.23而不是35.24 。默认的RoundingMode的DecimalFormat为HALF_EVEN,如果我使用RoundingMode.UP,我会得到正确的35.24,但其他结果将被弄乱,所以我卡住...

What should I use in order to get the expected result? 我应该使用什么才能获得预期的结果?

Using RoundingMode UNNECESSARY , will solve your problem. 使用RoundingMode UNNECESSARY可以解决您的问题。 Additionally you can catch exceptions and specify output manually if needed. 此外,您可以捕获异常并根据需要手动指定输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM