lualua-5.3

Managing Lua 5.3 ".0" behavior


In Lua 5.3, when a number is a float without any decimal part, printing it adds ".0" to the end of it, giving me the wrong answer in golf and speed competitions. Rounding or ~~x or x|0 forces it to be an integer type, but for a problem like "find the mean" which could be an integer or have decimals, simply printing sum/size will give the wrong answer every time it is an integer because it ends in ".0" instead of nothing. So then an extra check is needed, adding characters to code golf solutions and extra tests and time writing code to speed runs. Is there any good way to approach this behavior short of petitioning the contest holder to accept integers ending in ".0" in their answers?


Solution

  • Do not expect "print" to guess how you want your number formatted. If you want a specific format, use 'string.format'. For instance, string.format("%g", x) does not add .0 to numbers when they are integral values.