3
votes

Just noticed that tostring() and tonumber() in Lua is locale dependent. Any idea of how to convert a string to a number without using tonumber()? Thanks.

e.g. convert string "-58.5" to -58.5

Also when I tried to pass a number with dot to a function, the function converts "." to "," automatically. How do you usually solve this kind of problems?

function test(num) print(num) end

test(-58.5) -- it prints -58,5

1
Without tonumber? You could try adding 0 to the string. It should do automatic conversion for you. Probably still locale dependant. - warspyking

1 Answers

4
votes

The result of your test function is itself locale-dependent. (On my machine with default settings I get a result of -58.5 since my locale is en_US.UTF-8.)

You should be able to set the locale however you like via os.setlocale. That might be simpler than writing your own tonumber function.

For example:

local function nshow(n) print(n) end
local n = -58.5

print(os.setlocale("de_DE.UTF-8"))
nshow(n)
print(os.setlocale("C"))
nshow(n)

Output:

de_DE.UTF-8
-58,5
C
-58.5