Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua string.format ("%d") fails for some integers

I am using lua 5.3.2 and the following piece of code gives me an error:

string.format("%d", 1.16 * 100)

whereas the following line works fine

string.format("%d", 1.25 * 100)

This is probably related to this question but the failure depends on the floating point value. Given that, in my case, a local variable (v) holds the float value, and is generated by an expresson that produces a value between 0 and 2 rounded to 2 decimal places.

How can I modify the code to ensure this doesn't fail for any possible value of v ?

like image 626
koushik Avatar asked Feb 15 '26 12:02

koushik


1 Answers

You can use math.floor to convert to integer and add +0.5 if you need to round it: math.floor(1.16 * 100 + 0.5). Alternatively, "%.0f" should have the desired effect as well.

like image 86
Paul Kulchenko Avatar answered Feb 20 '26 01:02

Paul Kulchenko



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!