In my Lua code I need to do an operation that allows me to join two variables (an integer and a float) but without using the Adds (+) operator. How can I get this result?
local A = 12
local B = 0.2
local C = A ???? B
C = 12.2
You can achieve this by removing the decimal point from B
, then concatenating A
and B
using string.format()
, and finally converting the resulting string into a number with tonumber()
:
local A = 12
local B = 0.2
local C = tonumber(string.format("%d.%d", A, B*10))
print(C) --> 12.2
EDIT: If you have an arbitrary number of digits after the decimal point, you can use this function remove it:
function remove_decimal_point(n)
while n % 1 ~= 0 do
n = n * 10
end
return n
end
Then,
local A = 12
local B = 0.2
local C = tonumber(string.format("%d.%d", A, remove_decimal_point(B)))
print(C) --> 12.2