Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip trailing zeroes and decimal point

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.

like image 459
Thomas W Avatar asked Oct 23 '25 00:10

Thomas W


1 Answers

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.

like image 164
Oleg V. Volkov Avatar answered Oct 25 '25 18:10

Oleg V. Volkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!