Reputation: 2051
I have a string that contains a number in a Jsonnet variable. How do I convert it to an integer?
Upvotes: 5
Views: 3719
Reputation: 3131
Jsonnet's standard library provides a: std.parseInt(str)
function that can parse a signed decimal integer from a given input string.
For example:
std.parseInt("123") // yields 123
std.parseInt("-456") // yields -456
Reference: http://jsonnet.org/docs/stdlib.html
Upvotes: 7
Reputation: 2051
The Jsonnet standard library is fairly thin, but here is an example of a Jsonnet function that does this conversion.
{
string_to_int(s)::
local char_to_int(c) = std.codepoint(c) - std.codepoint("0");
local digits = std.map(char_to_int, std.stringChars(s));
std.foldr(function(x,y) x+y,
std.makeArray(std.length(digits),
function(x) digits[std.length(digits)-x-1]*std.pow(10, x)),
0),
}
Upvotes: -2