Jason
Jason

Reputation: 12789

How to format decimal places which contains different values

double d1 = "4.0"
double d2 = "4.2"
double d3 = "4.28"

I perform an arithmetic operation and it results in the above values with a maximum scale of 2. For d1, I would prefer that the value be formatted to a simple integer (e.g. 4 in this case) and the formatting on the rest of the values d2, d3 . How should I do this?

Upvotes: 0

Views: 219

Answers (1)

pstanton
pstanton

Reputation: 36640

Use a DecimalFormat

for example:

DecimalFormat df = new DecimalFormat("####0.##");
System.out.println(df.format(d1));
System.out.println(df.format(d2));
System.out.println(df.format(d3));

read the doc to get the best format pattern for your needs.

Upvotes: 4

Related Questions