Question

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?

Was it helpful?

Solution

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))

OTHER TIPS

Try this instead:

for s in (myString..","):gmatch("(%S+),") do print(s) end

I would suggest using the gsplit function defined here: SplitJoin, and then having a loop like so:

t = {}
for number in gsplit(myString:gsub('%s',''),',') do
    t[#t+1] = tonumber(number)
end

Which for a string:

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

the result of table.concat(t,',') is:

1,200,-100000

Here is another answer, which is robust but probably overkill:

f = loadstring("return {" .. myString .."}")
if f==nil then  end -- myString malformed
elements = f()

Extend the pattern to recognize optional mantissa and use tonumber to get the number from the string:

elements = {}
myString = "1.000000000000000E+00,  2.000000000000000E+02,  -1.000000000000000E+05"
for s in myString:gmatch('[+%-]?%d+%.?%d*[eE+%-]*%d?%d?') do
    table.insert(elements, tonumber(s))
end
print(unpack(elements))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top