使用Lua,我将数字格式化为可变数量的数字,并去除结尾的零/小数点之类的
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).
因此任务得以解决,但是出于美学,教育和性能方面的原因,我有兴趣了解是否存在一种更优雅的方法-可能仅使用一个gsub().
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是不可选择的,因为要避免科学计数法.
%g in string.format() is no option as scientific notation is to be avoided.
推荐答案如果您的精度始终> 0,则保证尾随字符是浮点数的0序列或.的后跟序列用于整数.因此,您可以识别并剥离此预告片",而其余字符串保留为:
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+$", "")它不会破坏以0结尾的整数,因为整数在有效零之后会具有浮点,因此它们不会在字符串末尾被"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.
如果precision为0,则根本不执行gsub.
If precision is 0, then you should simply not execute gsub at all.
更多推荐
去除尾随零和小数点
发布评论