user15477026
user15477026

Reputation:

Remove the one trailing zero for a String datatype

How can i remove the only trailing zero for a string datatype in java. For Example:

if the input value is 29.360 then the expected output should be 29.36

if the input value is 29.00 then the expected output should be 29.0

if the input value is 29.50 then the expected output should be 29.5

Upvotes: 0

Views: 67

Answers (2)

Uday Chauhan
Uday Chauhan

Reputation: 1148

You can use BigDecimal to achieve the same. Example is given below:

    System.out.println(new BigDecimal("29.360").stripTrailingZeros());
    System.out.println(new BigDecimal("29.00").stripTrailingZeros());
    System.out.println(new BigDecimal("29.50").stripTrailingZeros());

Upvotes: -1

WJS
WJS

Reputation: 40034

Try this.

  • "0$" matches a 0 at the end of the string.
  • and replaces all but that with an empty string if found.
  • (?<!\\.) says don't remove a lone 0 after the decimal point.
String[] data = {"29.360", "100", "1000","29.00", "33.47", "29.50", "29.0"}; 
for (String val : data) {
    String result = val.replaceAll("(\\d*\\.\\d*)(?<!\\.)0$","$1");
    System.out.println(val + " --> " + result);
}

prints

29.360 --> 29.36
100 --> 100
1000 --> 1000
29.00 --> 29.0
33.47 --> 33.47
29.50 --> 29.5
29.0 --> 29.0

Upvotes: 2

Related Questions