mirror of
https://github.com/JustinSDK/dotSCAD.git
synced 2025-08-19 04:51:26 +02:00
added parse_number
This commit is contained in:
@@ -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)
|
||||
|
12
docs/lib-parse_number.md
Normal file
12
docs/lib-parse_number.md
Normal file
@@ -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
|
32
src/parse_number.scad
Normal file
32
src/parse_number.scad
Normal file
@@ -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);
|
||||
|
Reference in New Issue
Block a user