Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zeros from double

I would like to remove all trailing zeros without truncating or rounding the number if it doesn't have any. For example, the number could be something like 12.0, in which case, the trailing zero should be removed. But the number could also be something almost irrational, like 12.9845927346958762... going on an on to the edge of the screen. Is there a way to setup DecimalFormat or some other class to cut of trailing zeros, while keeping the irrationality intact?

like image 365
Mohit Deshpande Avatar asked Jul 01 '12 19:07

Mohit Deshpande


People also ask

How do I get rid of trailing zeros?

Multiply by 1. A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.

How do you remove zeros from a double in Java?

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 trim trailing zeros in C++?

you can round-off the value to 2 digits after decimal, x = floor((x * 100) + 0.5)/100; and then print using printf to truncate any trailing zeros..


2 Answers

If you are willing to switch to BigDecimal, there is a #stripTrailingZeroes() method that accomplishes this.

like image 135
Keppil Avatar answered Sep 18 '22 13:09

Keppil


You can use String manipulation to remove trailing zeros.

private static String removeTrailingZeros(double d) {
  return String.valueOf(d).replaceAll("[0]*$", "").replaceAll(".$", "");
}

System.out.println(removeTrailingZeros(1234.23432400000));
System.out.println(removeTrailingZeros(12.0));
like image 42
sperumal Avatar answered Sep 20 '22 13:09

sperumal