With Lua, I'm formatting numbers to a variable number of digits and strip trailing zeroes/decimal points like
string.format(" %."..precision.."f", value):
gsub("(%..-)0*$", "%1"):
gsub("%.$", "")
Value is of type number (positive, negative, integer, fractional).
So the task is solved, but for aesthetic, educational and performance reasons I'm interested in learning whether there's a more elegant approach - possibly one that only uses one gsub()
.
%g
in string.format()
is no option as scientific notation is to be avoided.
If your precision is always > 0, then trailing characters are guaranteed to be either sequence of
0
for floats or.
followed by sequence of0
for integers. Therefore you can identify and strip this "trailer", leaving rest of the string with:It won't mangle integers ending in 0 because those would have float point after significant zeros so they won't get caught as "sequence of
0
right before end of string.If precision is 0, then you should simply not execute
gsub
at all.