How to match floating point number while reading a string

How can I match floating point numbers such as 1.234or that use "E notation", for example, 1.23e04when dealing with strings?

As an example, let's say that I would like to read numbers from a data file, for example:

0.0 1.295e-03
0.1 1.276e-03
0.2 1.261e-03
0.3 1.247e-03
0.4 1.232e-03
0.5 1.218e-03

At the moment, I have written my own function to convert each line to the numbers it contains, but it is not very elegant and not portable at all: data files with a different “layout” will give errors.

Here is a simple example that reads an already submitted data file and displays the numbers:

function read_line(str)
   local a, b, c, d, e = str:match(
      "^%s*(%d+)%.(%d+)%s+(%d+)%.(%d+)[Ee]%-*(%d+)")
   if str:match("%-") then
      e = -tonumber(e)
   end
   local v1 = a + .1*b
   local v2 = (c + .001*d) * 10^e
   return v1, v2
end

for line in io.lines("data.txt") do
   print(read_line(line))
end

and this results in:

0   0.001295
0.1 0.001276
0.2 0.001261
0.3 0.001247
0.4 0.001232
0.5 0.001218

This is really the result that I want to achieve, but is there a more elegant and general way to solve this problem?

. , "E".

+4
3

, , tonumber :

function split_number(str)
    local t = {}
    for n in str:gmatch("%S+") do
        table.insert(t, tonumber(n))
    end
    return table.unpack(t)
end

for line in io.lines("data.txt") do
    print(split_number(line))
end
+3

Lua :

f=assert(io.open("data.txt"))
while true do
    local a,b=f:read("*n","*n")
    if b==nil then break end
    print(a,b)
end
f:close()
+3

This works on lua REPL.

a = tonumber('4534.432')
b = tonumber('4534.432')
a==b 

So your answer is just to use tonumber.

+1
source

All Articles