I want to write a function that limits the string representation of a number to a specific number of decimals (in this example: 3 decimals). However, I also want to remove any trailing zeros at the end. So the following numbers should be transformed into the corresponding strings:
12.34567 -> "12.345" 10.50 -> "10.5" 12.00 -> "12" 0 -> "0"
I have looked into string patterns, and found out that the pattern
"%.3f" formats a number to have 3 decimals. However, that leaves trailing zeros at the end, which I want to avoid.
I could still use the pattern and then iteratively check if the last character of the string is a 0 and remove it, but then that leaves the dot behind. I could check for both dots and zeros, but then that would transform the number
"5", unless I add an additional check to stop after the first encounter of a dot. Either way, the resulting function would look oddly complex for a seemingly simple problem.
I am wondering, is there a better way of going about this?