Skip to content

Commit a823322

Browse files
committed
Allow converting to numbers
1 parent 48cef3c commit a823322

File tree

5 files changed

+35
-0
lines changed

5 files changed

+35
-0
lines changed

jsone.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,9 @@ var builtin = map[string]interface{}{
177177
return "", fmt.Errorf("str(value) only works on strings, numbers, booleans and null")
178178
}
179179
}),
180+
"number": i.WrapFunction(func(s string) (float64, error) {
181+
return strconv.ParseFloat(s, 64)
182+
}),
180183
"typeof": i.WrapFunction(func(v interface{}) interface{} {
181184
switch v.(type) {
182185
case string:

jsone/builtins.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ def lowercase(v):
8383

8484
builtin('len', argument_tests=[is_string_or_array])(len)
8585
builtin('str', argument_tests=[anything_except_array])(to_str)
86+
builtin('number', variadic=is_string, minArgs=1)(float)
8687

8788
@builtin('strip', argument_tests=[is_string])
8889
def strip(s):

jsone/newsfragments/240.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a `number` builtin that converts strings to numbers

specification.yml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1666,6 +1666,31 @@ context: {key: [1, 2, 3]}
16661666
template: {$eval: 'str(key)'}
16671667
error: 'BuiltinError: invalid arguments to builtin: str'
16681668
---
1669+
title: number
1670+
context: {round: "3"}
1671+
template: {foo: {$eval: number(round)}}
1672+
result: {foo: 3}
1673+
---
1674+
title: number (with point)
1675+
context: {round: "3.5"}
1676+
template: {foo: {$eval: number(round)}}
1677+
result: {foo: 3.5}
1678+
---
1679+
title: negative number
1680+
context: {round: "-14"}
1681+
template: {foo: {$eval: number(round)}}
1682+
result: {foo: -14}
1683+
---
1684+
title: negative number (with point)
1685+
context: {round: "-14.15"}
1686+
template: {foo: {$eval: number(round)}}
1687+
result: {foo: -14.15}
1688+
---
1689+
title: number zero
1690+
context: {round: "0"}
1691+
template: {foo: {$eval: number(round)}}
1692+
result: {foo: 0}
1693+
---
16691694
title: strip space
16701695
context: {}
16711696
template: {$eval: "strip(' abc ')"}

src/builtins.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,11 @@ module.exports = (context) => {
9191
},
9292
});
9393

94+
define('number', builtins, {
95+
argumentTests: ['string'],
96+
invoke: Number,
97+
});
98+
9499
define('len', builtins, {
95100
argumentTests: ['string|array'],
96101
invoke: obj => Array.from(obj).length,

0 commit comments

Comments
 (0)