1

I want to convert localized strings to numbers; including the decimal separator and/or thousands separator. It works for strings where there is only a "." as decimal separator, but won't work, i.e. returns nil, for the following cases:

  1. "21,1" (expected: 21.1)
  2. "1,231.0" (expected: 1231.0)
  3. "1.000.101,044" (expected: 1000101.044)

The problem is that I won't know which locale is set beforehand so the conversion must be generic.

Is there a locale-dependent string to number conversion?

ShitakeOishii
  • 89
  • 2
  • 9
  • How do you understand whether `tonumber(1.001)` should be `1001` or `1001/1000`? The dot might be thousands separator or a decimal point depending on the locale. – Egor Skriptunoff Dec 29 '21 at 05:23

1 Answers1

0

Sort of – there is no specific conversion function that would accept a locale, but it can be set for the whole process with os.setlocale:

assert(os.setlocale("de.utf8"))
print(tonumber("1,2"))

This sets the C locale to German (UTF-8), assuming it is installed on the system, which will affect all conversions, but also things like formatting, collation, time etc. You have to use os.setlocale(name, "numeric") to affect only number formatting and parsing rules.

You can do this multiple times, until the conversion succeeds.

IS4
  • 11,945
  • 2
  • 47
  • 86
  • I've read that in https://stackoverflow.com/questions/35003914/lua-convert-string-to-number-locale-dependent and tried it, but maybe it was just an interpreter error on https://www.lua.org/cgi-bin/demo. – ShitakeOishii Dec 27 '21 at 20:35
  • 1
    Unfortunately this only works partially, i.e. `print(tonumber("1.111,2"))` returns `nil`. I guess I will have to work with some workarounds to reformat whatever input I'm getting and enforce one locale. – ShitakeOishii Dec 27 '21 at 22:02
  • Ah it depends on the locales installed on the system, there is no guarantee that the demo will have it (and seems like I was incorrect in the name anyway, at least in the case of Unix). It's not platform-independent. – IS4 Dec 27 '21 at 22:13