Strip trailing zeroes and decimal point

2019-07-20 20:32发布

问题:

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.

回答1:

If your precision is always > 0, then trailing characters are guaranteed to be either sequence of 0 for floats or . followed by sequence of 0 for integers. Therefore you can identify and strip this "trailer", leaving rest of the string with:

string.format(" %."..precision.."f", value)
   :gsub("%.?0+$", "")

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.