Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing zero in a String value and remove decimal point [duplicate]

How do I remove trailing zeros in a String value and remove decimal point if the string contains only zeros after the decimal point? I'm using the below code:

String string1 = Double.valueOf(a).toString()

This removes trailing zeros in (10.10 and 10.2270), but I do not get my expected result for 1st and 2nd inputs.

Input

10.0
10.00
10.10
10.2270

Expected output

10
10
10.1
10.227
like image 866
Marjer Avatar asked Aug 28 '14 05:08

Marjer


People also ask

How do you get rid of trailing zero in decimals?

1. Using Decimal Numbers by Format Cells. First you have to select the cell in which you want to remove trailing zeros after the decimal point, right-click to the Format Cells from the context menu.

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 double trailing zeros?

Use a DecimalFormat object with a format string of "0. #".

How do I get rid of .00 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..


1 Answers

The Java library has a built-in class that can do this for it. It's BigDecimal.

Here is an example usage:

BigDecimal number = new BigDecimal("10.2270");  
System.out.println(number.stripTrailingZeros().toPlainString());

Output:

10.227

Note: It is important to use the BigDecimal constructor that takes a String. You probably don't want the one that takes a double.


Here's a method that will take a Collection<String> and return another Collection<String> of numbers with trailing zeros removed, gift wrapped.

public static Collection<String> stripZeros(Collection<String> numbers) {
    if (numbers == null) { 
        throw new NullPointerException("numbers is null");
    }

    ArrayList<String> value = new ArrayList<>(); 

    for (String number : numbers) { 
        value.add(new BigDecimal(number).stripTrailingZeros().toPlainString());
    }

    return Collections.unmodifiableList(value);
}

Example usage:

ArrayList<String> input = new ArrayList<String>() {{ 
    add("10.0"); add("10.00"); add("10.10"); add("10.2270"); 
}};

Collection<String> output = stripZeros(input);
System.out.println(output);

Outputs:

[10, 10, 10.1, 10.227]
like image 75
jdphenix Avatar answered Sep 16 '22 15:09

jdphenix