Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA How to remove trailing zeros from a double [duplicate]

For example I need 5.0 to become 5, or 4.3000 to become 4.3.

like image 346
Wrath Avatar asked Jan 07 '13 22:01

Wrath


People also ask

How do you get rid of double trailing zeros?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.

How do you remove trailing zeros from strings?

Algorithm. 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 get rid of trailing zeros in numbers?

Removing Same Number of trailing zeros by Formula 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.

What is DecimalFormat in Java?

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.


1 Answers

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 
like image 90
Marcin Szymczak Avatar answered Sep 19 '22 17:09

Marcin Szymczak