1

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.

randers
  • 5,031
  • 5
  • 37
  • 64
Randy Lust
  • 11
  • 3

1 Answers1

1

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
Community
  • 1
  • 1
Rochet2
  • 1,146
  • 1
  • 8
  • 13
  • Using your first method I would also extract it to a function and add `assert`: `local function mergeToDecimal( a, b ) local c = a .. "." .. b assert( tonumber( c ), "Could not convert number.") return c end mergeToDecimal( "10a", 12)` – Westerlund.io Jan 20 '16 at 21:39
  • This works sometimes, but b can be up to 4 digits. I am measuring temperature with a ds18b20 and it is returning a changing number of digits to b. – Randy Lust Jan 20 '16 at 21:46
  • @RandyLust Did you use the first or the second approach when you tested and had the changing digits in b? I changed the code very recently for the second approach because my math was wrong and only worked for the example case. – Rochet2 Jan 20 '16 at 22:22
  • I used method 2. 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 I had tried method 1 and got a nul. – Randy Lust Jan 20 '16 at 23:52
  • Sorry I do not see a change in the math. Thanks for the help! – Randy Lust Jan 21 '16 at 00:14
  • @RandyLust Despite your example, I suspect by "a changing number of digits" (up to 4) that if a represents the whole number and b the fraction, you need something like: a + b/10000 – tonypdmtr Jan 21 '16 at 19:06