procps/lib/test_strtod_nol.c
Craig Small 32e1b2e297 A locale-independent strtod
There is a need in some utilities to have a way of accepting both
types of decimal points "." and ",". The only way seems to be to
rebuild strtod().

This new function will accept "123.456" and "123,456" as 123.456
and considers them the same number. It means we lose thousands
separator, but this is rarely used.

test scripts are added to check the function returns the proper
values. There was simpler predecessor that got stuck on negative
0 or -0.123 which these tests flushed out.

References:
2016-03-03 21:24:08 +11:00

46 lines
972 B
C

#include <stdio.h>
#include <stdlib.h>
#include "strutils.h"
struct strtod_tests {
char *string;
double result;
};
struct strtod_tests tests[] = {
{"123", 123.0},
{"-123", -123.0},
{"12.34", 12.34},
{"-12.34", -12.34},
{".34", 0.34},
{"-.34", -0.34},
{"12,34", 12.34},
{"-12,34", -12.34},
{",34", 0.34},
{"-,34", -0.34},
{"0", 0.0},
{".0", 0.0},
{"0.0", 0.0},
{NULL, 0.0}
};
int main(int argc, char *argv[])
{
int i;
double val;
for(i=0; tests[i].string != NULL; i++) {
if(strtod_nol_or_err(tests[i].string, "Cannot parse number") !=
tests[i].result) {
fprintf(stderr, "FAIL: strtod_nol_or_err(\"%s\") != %f\n",
tests[i].string, tests[i].result);
return EXIT_FAILURE;
}
//fprintf(stderr, "PASS: strtod_nol for %s\n", tests[i].string);
}
return EXIT_SUCCESS;
}