# to_integer

Definition: | integer res = to_integer(string s, integer def_value = 0, base = 10)
Description: | Converts a string representation of a decimal integer into an actual integer. s: A string such as "42". def_value: The value to return on failure. base: The number base to use (2..36). Returns the integer equivalent of s, or def_value.
pwa/p2js: | Supported.
Comments: | This is, quite deliberately, just about the simplest possible implementation of such a function. Use to_number() to deal with values exceeding an integer, fractions, exponents, underscores, etc. By default to_integer(s) returns 0 for both "0" and "abc". To sidestep that kind of potential confusion there is a sister function, bool res = is_integer(string s[,base=10]), which obviously annihilates any such ambiguity. Note that to_integer("-1073741824") fails/returns def_value after having set sgn to -1 but then finding "1073741824" is not an integer (only just), and also that is_integer() actually depends on that behaviour (of to_integer), and likewise yields false for "-1073741824". (Of course that "-1073741824" is replaced with "-4611686018427387904" on 64bit.) Note that when base is 16 it is permitted for s to begin with ["+"/"-"] "#" or "0x"/"0X", however there is no such handling for "0b", "0o", "0t", or "0(base)" although you can of course crop off any such yourself.
Example: |
    ?to_integer("12")       --  12
    ?to_integer("-12")      -- -12
    ?to_integer("abc")      --   0 (the default def_value)
Implementation: | See builtins\to_int.e (an autoinclude) for details of the actual implementation.
See Also: | to_number