diff --git a/README.md b/README.md index ea294f6f..e8b4e688 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Some modules may depend on other modules. For example, the `polyline2d` module d - [rotate_p](https://openhome.cc/eGossip/OpenSCAD/lib-rotate_p.html) - [sub_str](https://openhome.cc/eGossip/OpenSCAD/lib-sub_str.html) - [split_str](https://openhome.cc/eGossip/OpenSCAD/lib-split_str.html) + - [parse_number](https://openhome.cc/eGossip/OpenSCAD/lib-parse_number.html) - Path - [circle_path](https://openhome.cc/eGossip/OpenSCAD/lib-circle_path.html) diff --git a/docs/lib-parse_number.md b/docs/lib-parse_number.md new file mode 100644 index 00000000..412b0838 --- /dev/null +++ b/docs/lib-parse_number.md @@ -0,0 +1,12 @@ +# parse_number + +Parses the string argument as an number. It depends on the `split_str` and the `sub_str` functions so remember to include split_str.scad and sub_str.scad. + +## Parameters + +- `t` : A String containing the number representation to be parsed. + +## Examples + + echo(parse_number("10") + 1); // ECHO: 11 + echo(parse_number("-1.1") + 1); // ECHO: -0.1 diff --git a/src/parse_number.scad b/src/parse_number.scad new file mode 100644 index 00000000..6dbc26f7 --- /dev/null +++ b/src/parse_number.scad @@ -0,0 +1,32 @@ +/** +* parse_number.scad +* +* Parses the string argument as an number. +* It depends on the split_str and the sub_str functions +* so remember to include split_str.scad and sub_str.scad. +* +* @copyright Justin Lin, 2017 +* @license https://opensource.org/licenses/lgpl-3.0.html +* +* @see https://openhome.cc/eGossip/OpenSCAD/lib-parse_number.html +* +**/ + +function _str_to_int(t, i = 0, mapper = [["0", 0], ["1", 1], ["2", 2], ["3", 3], ["4", 4], ["5", 5], ["6", 6], ["7", 7], ["8", 8], ["9", 9]]) = + i == len(mapper) ? -1 : ( + mapper[i][0] == t ? mapper[i][1] : _str_to_int(t, i + 1) + ); + +function _parse_positive_int(t, value = 0, i = 0) = + i == len(t) ? value : _parse_positive_int(t, value * pow(10, i) + _str_to_int(t[i]), i + 1); + +function _parse_positive_decimal(t, value = 0, i = 0) = + i == len(t) ? value : _parse_positive_decimal(t, value + _str_to_int(t[i]) * pow(10, -(i + 1)), i + 1); + +function _parse_positive_number(t) = + len(search(".", t)) == 0 ? _parse_positive_int(t) : + _parse_positive_int(split_str(t, ".")[0]) + _parse_positive_decimal(split_str(t, ".")[1]); + +function parse_number(t) = + t[0] == "-" ? -_parse_positive_number(sub_str(t, 1, len(t))) : _parse_positive_number(t); +