Josh Josh -4 years ago 122
Java Question

Removing the .0 from a double

I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86

Answer Source

Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download