Change 1.0, 2.0 like float values to 1 , 2 | remove trailing zeros from floating binary point types

I am receiving double values from API call .That method return this kind of values 2.0, 2.344, 2.034, 3.1 etc.

If I receive value like 2.0, 4.0, I want to convert them 2, 4. And I need do this conversions only 2.0, 3.0 like values.

How can I achieve this?

Jon Skeet

Assuming this is a matter of formatting a double value as a String, ensuring there are no trailing insignificant zeroes, I'd advise using a DecimalFormat to control the formatting. For example:

import java.text.*;
import java.util.*;

class Test {
    public static void main(String[] args) throws Exception {

    private static void print(double value) {
        NumberFormat format = new DecimalFormat(
        String text = format.format(value);

Note the use of Locale.US to always end up with a dot as the decimal separator.

The final example in main shows the limitations here - numbers very close to 0 will be formatted as "0", as I haven't provided enough optional digits (the # parts) to format them more appropriately. It's not clear what you want in those cases anyway though; the default representation would be 1.2345E-46.


See more on this question at Stackoverflow