Search code examples
javadoublelong-integer

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);
System.out.println(output);

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


Solution

  • Use DecimalFormat

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