Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow tonumber to work on strings that contain commas as thousands separators #1102

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -329,12 +329,28 @@ static jv f_json_parse(jq_state *jq, jv input) {
return res;
}

static void remove_commas(const char *input, char *output) {
int index_from = 0;
int index_to = 0;
while (input[index_from] != 0) {
output[index_to++] = input[index_from++];
while (input[index_from] == ',') {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leading commas won't be removed. Why remove multiple contiguous commas?

index_from++;
}
}
output[index_to] = 0;
}

static jv f_tonumber(jq_state *jq, jv input) {
if (jv_get_kind(input) == JV_KIND_NUMBER) {
return input;
}
if (jv_get_kind(input) == JV_KIND_STRING) {
jv parsed = jv_parse(jv_string_value(input));
const char * input_string = jv_string_value(input);
char * commaless_string = (char *) malloc(strlen(input_string) + 1);
remove_commas(input_string, commaless_string);
jv parsed = jv_parse(commaless_string);
free(commaless_string);
if (!jv_is_valid(parsed) || jv_get_kind(parsed) == JV_KIND_NUMBER) {
jv_free(input);
return parsed;
Expand Down