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".