Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 267
Josh Avatar asked Aug 18 '11 14:08

Josh


People also ask

How do you get rid of double trailing zeros?

format(doubleVal); // This ensures no trailing zeroes and no separator if fraction part is 0 (there's a special method setDecimalSeparatorAlwaysShown(false) for that, but it seems to be already disabled by default).

How do you remove trailing zeros from strings?

Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.

How do you remove the last zero of a number?

In case you want to remove the same numbers of zeros from the end, you can apply a formula to solve it. Select the adjacent cell to the number you used. Type this formula =LEFT(D1, LEN(D4)-2)*1, D4 is the cell you will remove trailing zeros from, 2 is the number of zeros you want to remove.


2 Answers

Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
like image 170
Kal Avatar answered Oct 07 '22 12:10

Kal


The DecimalFormat suggestions are the easiest way to handle this. If they aren't sufficient, here's another idea.

If you're starting to hit the maximum values that can be represented by primitives in Java, then you may need to move to BigInteger and BigDecimal.

Try playing around with the BigDecimal.toBigInteger() method coupled with the toString() methods on BigDecimal and BigInteger.

like image 23
Ophidian Avatar answered Oct 07 '22 13:10

Ophidian