removeTailZero function

String removeTailZero(
  1. String src
)

Removes trailing zeros from a numeric string.

A string without a decimal point is returned unchanged: its trailing zeros are significant digits of the integer part. In a string with a decimal point, the trailing zeros after the point are removed, and the point itself too when no digits remain after it ("100." becomes "100"). If nothing is left of such a string (".0"), the result is "0".

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"
removeTailZero("100");      // Returns "100"

Implementation

String removeTailZero(String src) {
  if (!src.contains('.')) {
    return 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;
  }

  String result = src.substring(0, src.length - pos);
  return result.isEmpty ? '0' : result;
}