3

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

mile
  • 402
  • 1
  • 6
  • 15
  • Without tonumber? You could try adding 0 to the string. It should do automatic conversion for you. Probably still locale dependant. – warspyking Jan 26 '16 at 00:26

1 Answers1

4

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
Telemachus
  • 19,459
  • 7
  • 57
  • 79
  • Thanks. The control system where the code is running doesn't allow os.setlocale(). Anyway, I used a workaround to get the decimal separator and then replace "." of the tonumber() input with the decimal separator. – mile Jan 26 '16 at 22:34
  • And apparently Lua does not handle thousands separators correctly in `tonumber` either. – stefanct Feb 13 '18 at 00:50