Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - gmatch scientific notation string to number

I am trying to convert a string of scientific notation numbers into actual numbers.

My test string is formatted like so:

myString = 1.000000000000000E+00,  2.000000000000000E+02,  -1.000000000000000E+05

My current code:

elements = {}

for s in myString:gmatch('%d+%.?%d*') do
    table.insert(elements, s);
end

return unpack(elements);

Elements returns the following incorrectly:

1.000000000000000     %from the first number before "E"
00                    %after the "E" in the first number
2.000000000000000     %from the second number before "E"

Anyone know how I can go about fixing this?

like image 716
MrHappyAsthma Avatar asked Oct 20 '25 21:10

MrHappyAsthma


2 Answers

To me, "actual numbers" means the number data type. tonumber() does quite well with scientific notation.

local myString = [[ 1.000000000000000E+00, 
 2.000000000000000E+02,  -1.000000000000000E+05 ]]
local function convert(csv)
    local list = {}
    for value in (csv .. ","):gmatch("(%S+)%W*,") do table.insert(list,tonumber(value)) end
    return unpack(list)
end
print(convert(myString))
like image 176
Tom Blodget Avatar answered Oct 22 '25 16:10

Tom Blodget


Try this instead:

for s in (myString..","):gmatch("(%S+),") do print(s) end
like image 35
lhf Avatar answered Oct 22 '25 14:10

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!