user5549921
user5549921

Reputation:

Remove '.0' from double, but keep every other possibility

I've seen a bunch of questions here on Stackoverflow referring to hiding the .0 after a double, but every single answer says to use DecimalFormat and do #.# to hide it. Except this is not what I want.

For every single possibility where the double does NOT end in simply .0, I want them to be how they are. Except when it DOES end in .0, remove it. In other words, I want to keep my precision at all times, unless it ends with a .0.

Examples:

0.0000000000000000042345470000230 -> 0.0000000000000000042345470000230
0.4395083451 -> 0.4395083451
46547453.00024235 -> 46547453.00024235

435.0 -> 435

Is there a way I can achieve this?

Further example:

This question here has the type of answer I am talking about:

Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));

The ###.# above means that I am going to have the first 3 digits appear, a period, and then the first number after it. Regardless of my value, only the first fractional number will be formatted.

Upvotes: 0

Views: 254

Answers (1)

3vts
3vts

Reputation: 828

Well actually it's not complicated at all. Just check this (It even gives you the most precise number):

//Square root of 5 will give you a lot of decimals    
BigDecimal d1 = new BigDecimal(sqrt(5));
//5 will give you none
BigDecimal d2 = new BigDecimal(5);
//Print and enjoy
System.out.println(d1.stripTrailingZeros());
System.out.println(d2.stripTrailingZeros());

The stripTrailingZeros() will remove any trail of plain 0's, but keep the formatting if other numbers are present.

Upvotes: 1

Related Questions