Skip to content

Commit 3cea53f

Browse files
bigbugmattbaileyuk
authored andcommitted
Binary/Octal/Hexadecimal numbers
1 parent b97c9d7 commit 3cea53f

File tree

5 files changed

+22
-0
lines changed

5 files changed

+22
-0
lines changed

docs/numeric-functions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@ __Signature:__ `$number(arg)`
1010
Casts the `arg` parameter to a number using the following casting rules
1111
- Numbers are unchanged
1212
- Strings that contain a sequence of characters that represent a legal JSON number are converted to that number
13+
- Hexadecimal numbers start with `0x`, Octal numbers with `0o`, binary numbers with `0b`
1314
- Boolean `true` casts to `1`, Boolean `false` casts to `0`
1415
- All other values cause an error to be thrown.
1516

1617
If `arg` is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of `arg`.
1718

1819
__Examples__
1920
- `$number("5")` => `5`
21+
- `$number("0x12")` => `0x18`
2022
- `["1", "2", "3", "4", "5"].$number()` => `[1, 2, 3, 4, 5]`
2123

2224

src/functions.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,6 +1202,8 @@ const functions = (() => {
12021202
result = arg;
12031203
} else if (typeof arg === 'string' && /^-?[0-9]+(\.[0-9]+)?([Ee][-+]?[0-9]+)?$/.test(arg) && !isNaN(parseFloat(arg)) && isFinite(arg)) {
12041204
result = parseFloat(arg);
1205+
} else if (typeof arg === 'string' && /^(0[xX][0-9A-Fa-f]+)|(0[oO][0-7]+)|(0[bB][0-1]+)$/.test(arg)) {
1206+
result = Number(arg);
12051207
} else if (arg === true) {
12061208
// boolean true casts to 1
12071209
result = 1;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"expr": "$number('0x12')",
3+
"dataset": null,
4+
"bindings": {},
5+
"result": 18
6+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"expr": "$number('0B101')",
3+
"dataset": null,
4+
"bindings": {},
5+
"result": 5
6+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"expr": "$number('0O12')",
3+
"dataset": null,
4+
"bindings": {},
5+
"result": 10
6+
}

0 commit comments

Comments
 (0)