Say you have a table of numbers like so
local numbers = {0.3000, 0.214000, 1.0000, 2.300, 3.39000} ---> 0.3, 0.213, 1, 2.3, 3.39
You see all the zeros at the end that's unnecessary, how do I go about removing them...
Say you have a table of numbers like so
local numbers = {0.3000, 0.214000, 1.0000, 2.300, 3.39000} ---> 0.3, 0.213, 1, 2.3, 3.39
You see all the zeros at the end that's unnecessary, how do I go about removing them...
I think math.abs() is what you're looking for.
print(math.abs(0.300000)) --> 0.3
print(math.abs(3.3900000)) --> 3.39
If this help, then please accept this answer!
That function returns the absolute value of what is passed in. An absolute value is the non-negative value. Basically disregard the negative sign of a negative number.
Adding onto Tyler090130's answer: Since we cannot have negatives due to the absolute function, we can store the sign first.
local function RoundDecimal(Number)
local Sign = Number/math.abs(Number)
local Rounded = math.abs(Number)
local Signed = Rounded * Sign
return Signed
end
RoundDecimal(-0.53000)
-- -0.53/0.53 = -1
-- abs(-0.53000) = 0.53
-- 0.53 * -1 = -0.53
Well this is messy, but the proper way to do this is to split each number into its characters by turning it into a string then using string.split
Next, you can iterate from the last digit to the first and if you hit either a number that is not 0 or a period, the rest of the string should be added back
Join the separated characters, convert back to a number, and add them to a new table and voila, you have a table with only the sig figs.
local numbers = {0.3000, 0.214000, 1.0000, 2.300, 3.39000}
local result = {}
for _, num in pairs(numbers) do
local ntbl = string.split(num, "")
local ftbl = {}
local flag = false
for c = #ntbl, 0, -1 do
if flag == true then
table.insert(ftbl, 1, ntbl[c])
else
local cnum = tonumber(c)
if c == "." then
flag = true
elseif cnum and cnum > 0 then
flag = true
table.insert(ftbl, 1, ntbl[c])
end
end
end
local txt = ""
for fk, fv in pairs(ftbl) do
txt = txt..""..fv
end
local fnum = tonumber(txt)
table.insert(result, (#result + 1), fnum)
end
"result" is the table with the updated numbers
Does this work with a number like 0.020503 or something? just asking.
This discussion is preserved as it was. New answers, comments, and votes are closed.
2 comments
What are you trying to say?
Is there more code to this or can you explain some more? Do you not know where the backspace key is?