据我了解,RoundingMode.HALF_UP 使用我们传统的舍入方式。但是,它没有给我想要的结果:
我正在使用具有不同参数(#、#.#、...等)的 DecimalFormat() 并输入 double 3.5545
// taken from Util
public static void setRound(int a) // Set rounding decimal places
{
roundTo = a;
String t = "#";
if (roundTo > 0)
{
t += ".";
for (int u = 1; u <= roundTo; u++)
t += "#";
}
df = new DecimalFormat(t);
df.setRoundingMode(RoundingMode.HALF_UP);
}
public static String round(double d) // Rounds up answers to set place
{
return df.format(d);
}
// taken from Testing class
for (int a = 0; a < 5; a++)
{
Util.setRound(a);
System.out.println(Util.round(3.5545));
}
// results
0 -> 4
1 -> 3.6
2 -> 3.55
3 -> 3.554 *(I want 3.555)*
4 -> 3.5545
我怎样才能解决这个问题(任何数字尾随 5 轮)? 任何帮助将不胜感激。
谢谢。
最佳答案
您可以使用 BigDecimal 缩放方法,例如;
for (int i = 0; i < 5; i++) {
BigDecimal bg = new BigDecimal("3.5545").setScale(i, RoundingMode.HALF_UP);
System.out.println(bg);
}
输出;
0 --> 4
1 --> 3.6
2 --> 3.55
3 --> 3.555
4 --> 3.5545
关于java - RoundingMode HALF_UP 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37536510/