removeTailZero function

String removeTailZero(
  1. String src
)

Removes trailing zeros from a numeric string.

Removes trailing zeros after the decimal point, and also removes the decimal point itself if no significant digits remain after it.

Parameters:

  • src The numeric string to process

Returns: String with trailing zeros removed

Example:

removeTailZero("123.4500"); // Returns "123.45"
removeTailZero("100.000");  // Returns "100"
removeTailZero("5.0");      // Returns "5"

Implementation

String removeTailZero(String src) {
  int pos = 0;
  for (int i = src.length - 1; i >= 0; i--) {
    if (src[i] == '0')
      pos++;
    else if (src[i] == '.') {
      pos++;
      break;
    } else
      break;
  }

  return src.substring(0, src.length - pos);
}