Trim zeros from decimal string

I came across one interesting requirement, where I had to clip zero's from the decimal formatted string. Sharing the code below.

Requirement



  • X.Y000 as X.Y
  • 0.1000 as 0.1
  • 1.000 as 1
Java method:



private static final Pattern TRAILING_ZERO = Pattern.compile("[.]{1}[0-9]*(0)+$");
       public static String removeTrailingZeros(String digit){
              if(digit==null)return digit;
              Matcher m=TRAILING_ZERO.matcher(digit);
              if(m.find()){
                     digit=digit.replaceAll("0*$", "");
                     if(digit.endsWith("."))
                           digit=digit.replace(".", "");
              }
              return digit;
       }
 

Comments

Popular posts from this blog

Delete horizontal, vertical and angled lines from an image using Python to clear noise and read text with minimum errors

Unordered JSON compare for differences using javascript

Java Currency Formatter Changing $ to ¤