Reputation: 11
I have 2 integer variables that I want to covert to a decimal integer. The result should be like this:
a = 10
b = 12
c = 10.12
I can convert them with concatenate to a string decimal but then I cannot use math functions on the result. I have tried to use tonumber()
on the string but I got a nil
value.
Upvotes: 1
Views: 1556
Reputation: 1156
I assume in the beginning a
and b
are integers and you wanted to join them so that a
is the integer part of the resulting number and b
is the decimal part - the part after the comma or dot in a double or float.
This is the string concat solution you suggested which works fine for me
a = 10
b = 12
c = tonumber(a..'.'..b)
print(c) -- prints 10.12
Here we are using math to calculate amount to divide b
to get it as the correct decimal and then we add it to a
. The code for determining the power of 10 was found here: How can I count the digits in an integer without a string cast?
a = 10
b = 12
c = a + b / math.pow(10, b == 0 and 1 or math.floor(math.log(math.abs(b), 10))+1)
print(c) -- prints 10.12
Upvotes: 1