This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
ikon106's profile picture

[Math] How To Make A Variable Into A Decimal

Started by ikon106, 08 October 2013 - 07:25 AM
ikon106 #1
Posted 08 October 2013 - 09:25 AM
Hello Pros!
I want to be able to turn x into 1.x but simply x = 1.x doesn't work, it gives the error 'For input string: "1.x"'. How can I make this work? I am pretty familiar with lua and CC so no need to "dumb it down" too much ;)/>

Thank you,
ikon106
LBPHacker #2
Posted 08 October 2013 - 09:47 AM
Either convert it into a string, concatenate it with "1." and then turn the result into a number:
function toDecimal(num)
    return tonumber("1." .. tostring(num))
end
or use log10 and some maths:
function toDecimal(num)
    return num / (10 ^ (math.floor(math.log10(num)) + 1)) + 1
end
ikon106 #3
Posted 08 October 2013 - 11:03 AM
Either convert it into a string, concatenate it with "1." and then turn the result into a number:
function toDecimal(num)
	return tonumber("1." .. tostring(num))
end

Thank you, is (num) x in my case? Or should I just copypaste exactly what you wrote?
mark332 #4
Posted 08 October 2013 - 11:50 AM
You may use it like this:

x = toDecimal(2)

this will set x as 1.2
Kingdaro #5
Posted 08 October 2013 - 12:36 PM
Wouldn't this work?


base = 1
deci = 2
x = base + deci / 10
print(x) --> 1.2
LBPHacker #6
Posted 08 October 2013 - 12:53 PM
-snip-
It would if deci had only one digit.
ikon106 #7
Posted 09 October 2013 - 05:44 AM
Thank you LBPHacker and Mark332 for the answers. It worked ;D