Best way to trim trailing zeros?

So I want to replace "31.100" for "31.1" and "31.000" to "31" and I couldn't find any buitin function to do one so I ended up with this. Do you have a better one?

function stripTrailingZeros(value) {
    if (value instanceof Lang.String) {
		if (value.find(".") != null) { // Only mathers if we contain a decimal
			var carray = value.toCharArray();
			var i = carray.size() - 1;
			for (; i > 0; i--) {
				if (carray[i].equals('.')) { // If we reached the '.', we'll skip it too and stop so we don't drop zeros before '.'
					i--;
					break;
				}
				if (carray[i].equals('0')) { // Trailing zero? Keep going
					continue;
				}

				break; // Not one of the above, so that's where we stop
			}
			value = "";
			for (var j = 0; j <= i; j++) {
				value += carray[j];
			}
		}
	}
	return value;
}

Top Replies

  • Maybe worth to read about the formats and play a bit with it, there might be a modifier that would do almost what you want, and if you're lucky with that, then all you're left to do is to…

All Replies

  • One problem with my latest answer is that it rounds the original value before determining the number of decimal places, but then it rounds the original value again with "%0.xf" for display. While it seems to produce the right answer for the test cases I tried, it doesn't seem quite right.

    Here's a better version that only rounds once (before counting decimals) and doesn't rely on the behaviour of "%0.xf" at all.

    It has the same problem that it won't work with either a large input value and/or a large maxDecimals value, but again that can be worked around by using toLong() instead of toNumber() at the initial rounding step.

    https://pastebin.com/PtCYgt4B 

    This algorithm displays 100.555 with a max of 2 places as "100.56", which makes more sense to me than the behaviour of "%0.2f", which produces "100.55" in both Monkey C and C (although other inputs seem to be rounded as expected [*])

    [*] round to nearest, and round up if there's a tie.

    Honestly I think this is an ok solution for this use case, where the final value is only used for display purposes, and where the original value is to be rounded to a *specified* number of decimal places (maxDecimals in the code above).

    It doesn't have much of an advantage over using "%0.xf" first and simply counting the number of decimals, except that it gives you full control over how the value is initially rounded.

    Obviously it wouldn't work for the generic case where you're not rounding numbers before counting decimals. It only works when you can specify a max number of decimals.