小数点后的固定位数

Fixed amount of digits after the decimal

我有很多 double 个数字来描述不同的对象。

例如:

 Object A
    double a = 10.12
    double b = 10.1223
    double c = 10.12345

 Object B
    double a = 10.12
    double b = 10.1223
    double c = 10.12345

...我希望小数点后有固定数量的数字,例如对象 A 必须在小数点后有 5(五)位数字,对象 B 必须在小数点后有 2(二)位数字并四舍五入。我想实现这样的目标:

 Object A
    10.12000
    10.12230
    10.12345

Object B
    10.12
    10.12
    10.12

我尝试 setMinimumFractionDigits(5)setMinimumFractionDigits(2) 并且它有效,但我有很多对象,首先必须在小数点后有一位数字,其他需要 5 等。这是一个大项目,是面向对象的。

知道我怎样才能做到这一点吗?

请通过创建 DecimalFormat obj 更改您的代码,并将其用于格式化 Double 个对象。

private static DecimalFormat fiveDigitFormat= new DecimalFormat(".#####");
private static DecimalFormat twoDigitFormat= new DecimalFormat(".##");

fiveDigitFormat.format(objA);
twoDigitFormat.format(objB);

如评论中所述,查看DecimalFormat

对你来说,它看起来像下面这样:

// For Object A
DecimalFormat dfForObjA = new DecimalFormat("#.#####");
dfForObjA.setRoundingMode(RoundingMode.CEILING);
for (double d : A) {   // Assuming A is already declared and initialized
    System.out.println(dfForObjA.format(d));
}

// For Object B
DecimalFormat dfForObjB = new DecimalFormat("#.##");
dfForObjB.setRoundingMode(RoundingMode.CEILING);
for (double d : B) {   // Assuming B is already declared and initialized
    System.out.println(dfForObjB.format(d));
}

注意:对于 for each 循环,我不太确定如何使用您的对象准确地实现它,因为不清楚它们到底是什么或它们是如何定义的.

您也可以简单地使用:

double a = 10.12;
double b = 10.1223;
double c = 10.12345;
System.out.println(String.format("%.5f", a));
System.out.println(String.format("%.5f", b));
System.out.println(String.format("%.2f", c));

它打印:

10.12000
10.12230
10.12