Strip trailing zeroes and decimal point

和自甴很熟 提交于 2019-12-11 03:56:55

问题


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.



来源:https://stackoverflow.com/questions/24697848/strip-trailing-zeroes-and-decimal-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!