CeZet
CeZet

Reputation: 1513

Fixed amount of digits after the decimal

I have many double numbers which describes different objects.

For example:

 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

...and I want have fixed amount of digits after decimal, for example Object A must have 5 (five) digits after decimal and Object B must have 2 (two) digits after decimal with rounding up. I want achieve something like this :

 Object A
    10.12000
    10.12230
    10.12345

Object B
    10.12
    10.12
    10.12

I try setMinimumFractionDigits(5) or setMinimumFractionDigits(2) and it works but I have many objects and first must have one digit after decimal other need 5 etc. This is big project and is object-oriented.

Any idea how can I achieve this ?

Upvotes: 1

Views: 101

Answers (3)

elias
elias

Reputation: 15510

You can also simply use:

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));

It prints:

10.12000
10.12230
10.12

Upvotes: 1

Harisudan Kuppusami
Harisudan Kuppusami

Reputation: 321

Please change your code by creating DecimalFormat obj and use it for formatting Double objects.

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

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

Upvotes: 2

sparkhee93
sparkhee93

Reputation: 1375

Like mentioned in the comment, check out DecimalFormat.

For you, it would look like the following:

// 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));
}

Note: For the for each loop, I'm not too sure how to implement it exactly with your objects since it's unclear what they exactly are or how they're defined.

Upvotes: 1

Related Questions