Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zero in Java

Tags:

java

string

regex

I have Strings (from DB), which may contain numeric values. If it contains numeric values, I'd like to remove trailing zeros such as:

  • 10.0000
  • 10.234000

str.replaceAll("\\.0*$", ""), works on the first one, but not the second one.

A lot of the answers point to use BigDecimal, but the String I get may not be numeric. So I think a better solution probably is through the Regex.

like image 863
fivelements Avatar asked Feb 20 '13 16:02

fivelements


People also ask

How do I get rid of trailing zeros in Java?

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. So basically the function trims off the trailing zero from the BigDecimal value.

How do you remove trailing zeros from a string?

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 remove leading and trailing zeros in Java?

Java For Testers The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. The ^0+(?! $)"; To remove the leading zeros from a string pass this as first parameter and “” as second parameter.

How do I remove a trailing character in Java?

Using StringBuildersetLength() instead of StringBuilder. deleteCharAt() when we remove trailing zeroes because it also deletes the last few characters and it's more performant.


1 Answers

there are possibilities:

1000    -> 1000 10.000  -> 10 (without point in result) 10.0100 -> 10.01  10.1234 -> 10.1234 

I am lazy and stupid, just

s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", ""); 

Same solution using contains instead of indexOf as mentioned in some of the comments for easy understanding

 s = s.contains(".") ? s.replaceAll("0*$","").replaceAll("\\.$","") : s 
like image 92
Kent Avatar answered Sep 18 '22 13:09

Kent