Skip to content

is_str_num() is not handling negative numbers #1109

@rtxa

Description

@rtxa

The is_str_num() function in string_stocks.inc currently does not handle negative numbers. The function only checks for the presence of digits in the string, without considering a leading negative sign which may be useful in some cases and that makes the function name misleading.

Updating is_str_num() may affect any existing code that relies on that behaviour, so maybe a new stock like is_str_num_ex() would be needed or a new optional parameter to allow negative numbers check. A note warning about this would be useful too.

Proposed fix

stock bool:is_str_num_ex(const sString[]) {
    new i = 0;
    new bool:is_negative = false;

    if (sString[0] == '-') {
        is_negative = true;
        i++;
    }

    while (sString[i] && isdigit(sString[i])) {
        i++;
    }

    return sString[i] == 0 && i != (is_negative ? 1 : 0);
}

Test code:

		server_print("Is str '' num? %d", is_str_num_ex(""));
		server_print("Is str '--' num? %d", is_str_num_ex("--"));
		server_print("Is str '-' num? %d", is_str_num_ex("-"));
		server_print("Is str '-0' num? %d", is_str_num_ex("-0"));
		server_print("Is str '0' num? %d", is_str_num_ex("0"));
		server_print("Is str '1000' num? %d", is_str_num_ex("1000"));
		server_print("Is str '-1000' num? %d", is_str_num_ex("-1000"));

Output:

Is str '' num? 0
Is str '--' num? 0
Is str '-' num? 0
Is str '-0' num? 1
Is str '0' num? 1
Is str '1000' num? 1
Is str '-1000' num? 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions