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

Caused by: java.sql.SQLTimeoutException: ORA-01013: user requested cancel of current operation

HashiCorp Vault Integration with Ansible Etower using approle

utility to extract date from text with java