How to remove trailing zeros from a double
126,056
Solution 1
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
Solution 2
You should use DecimalFormat("0.#")
For 4.3000
Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
output is:
4.3
In case of 5.000 we have
Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
And the output is:
5
Solution 3
Use a DecimalFormat object with a format string of "0.#".
Author by
Wrath
Updated on December 31, 2021Comments
-
Wrath over 2 years
For example I need
5.0
to become5
, or4.3000
to become4.3
. -
Peter Elliott over 11 yearsthis fails the case of
5.0
becoming5
, as it will always add a.0
to the end of numbers. -
Marcin Szymczak over 11 yearsThank you for Your comment. Now I have figured out that I should have used 0.#.
-
David Conrad over 10 yearsthis fails in the case of
4.32
which becomes4.3
-
VikrantY almost 10 yearsWon't this round the numnber like in case of 5.000001
-
Mostafa Zeinali about 9 yearsIt does and that's why this is wrong...
-
narancs about 8 yearsthis fails in the case of 4.32 which becomes 4.3
-
dashrb about 8 yearsfair point, although the OP didn't indicate how many places were desired. I can't think of a good reason to truncate trailing 0's but keep non-zeros as far as they are printable. IMHO, when printing a double, the code should specify the desired number of digits of precision (the number of #'s after the period).
-
Uncle Iroh almost 8 years@Karoly DecimalFormat df = new DecimalFormat("###.##"); df.setRoundingMode(RoundingMode.HALF_UP); System.err.println(df.format(4.325)); System.err.println(df.format(4.30)); System.err.println(df.format(4.00));
-
Chisko over 7 years@DavidConrad yes, because it is specifying only one decimal digit precision
-
David Conrad over 7 years@Chisko The question asks how to "remove trailing zeros".
-
Chisko over 7 yearsBut the description clarifies
-
Mohit Rajput over 5 yearsIt fails, 4.300001 becomes 4.3 and if you want to convert it to double, it will add .0 again.
-
JU5T1C3 over 5 yearsbe aware that the output is 4,3 and not 4.3
-
Rok Povsic about 5 yearsA double type can't really do this. If you're willing to switch to BigDecimal, here's the solution.
-
fHate almost 4 yearsBut how to be with values like 0.0005000 (must shown as 0.0005)?
-
Peter Schorn over 3 years@dashrb The OP was very explicit about what he wanted. He wants to remove trailing zeroes. Do you understand what the word "trailing" means?
-
Prabhat Gaur over 3 years@UncleIroh FYI this provides correct solution even after removing the RoundingMode.HALF_UP but keeping #.###