Number Parsing in Scilab

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Scilab.

// Scilab doesn't have a dedicated package for string to number conversion
// These operations are built into the language

// With strtod, we can parse floating-point numbers
f = strtod("1.234")
disp(f)

// For integer parsing, we can use int
i = int("123")
disp(i)

// Scilab recognizes hex-formatted numbers with '0x' prefix
d = int("0x1c8")
disp(d)

// For unsigned integers, we can use uint32 or uint64
u = uint32("789")
disp(u)

// There's no direct equivalent to Atoi, but we can use int
k = int("135")
disp(k)

// Error handling for invalid input
try
    e = int("wat")
catch
    disp(lasterror())
end

To run the program, save it as number_parsing.sce and execute it in Scilab:

--> exec('number_parsing.sce', -1)
    1.234
    123.
    456.
    789.
    135.
    Invalid conversion.

In Scilab, number parsing is more straightforward as the conversion functions are built into the language. The strtod function is used for parsing floating-point numbers, while int can be used for parsing integers.

For hexadecimal numbers, Scilab recognizes the ‘0x’ prefix automatically when using int.

Scilab doesn’t have separate unsigned integer types, but you can use uint32 or uint64 if you specifically need unsigned integers.

Error handling in Scilab is done using try-catch blocks. When an invalid conversion is attempted, Scilab throws an error which can be caught and handled.

Next, we’ll look at another common parsing task: URLs.