简体   繁体   中英

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

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

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM