test_locale.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stddef.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include "config.h"
  7. #include "json.h"
  8. #include "json_tokener.h"
  9. #include "snprintf_compat.h"
  10. #ifdef HAVE_LOCALE_H
  11. #include <locale.h>
  12. #endif /* HAVE_LOCALE_H */
  13. #ifdef HAVE_XLOCALE_H
  14. #include <xlocale.h>
  15. #endif
  16. int main(int argc, char **argv)
  17. {
  18. json_object *new_obj;
  19. #ifdef HAVE_SETLOCALE
  20. setlocale(LC_NUMERIC, "de_DE");
  21. #else
  22. printf("No locale\n");
  23. #endif
  24. char buf1[10], buf2[10];
  25. // Should result in "0,1", if the locale is installed.
  26. // Regardless of what it generates, we check that it's
  27. // consistent below.
  28. (void)snprintf(buf1, sizeof(buf1), "%f", 0.1);
  29. MC_SET_DEBUG(1);
  30. new_obj = json_tokener_parse("[1.2,3.4,123456.78,5.0,2.3e10]");
  31. (void)snprintf(buf2, sizeof(buf2), "%f", 0.1);
  32. if (strcmp(buf1, buf2) != 0)
  33. printf("ERROR: Original locale not restored \"%s\" != \"%s\"",
  34. buf1, buf2);
  35. #ifdef HAVE_SETLOCALE
  36. setlocale(LC_NUMERIC, "C");
  37. #endif
  38. // Explicitly print each value, to avoid having the "special"
  39. // serialization done for parsed doubles simply re-emit the original
  40. // string that was parsed. (see json_object_new_double_s())
  41. printf("new_obj.to_string()=[");
  42. unsigned int ii;
  43. for (ii = 0 ; ii < json_object_array_length(new_obj); ii++)
  44. {
  45. json_object *val = json_object_array_get_idx(new_obj, ii);
  46. printf("%s%.2lf", (ii > 0) ? "," : "", json_object_get_double(val));
  47. }
  48. printf("]\n");
  49. printf("new_obj.to_string()=%s\n", json_object_to_json_string_ext(new_obj,JSON_C_TO_STRING_NOZERO));
  50. json_object_put(new_obj);
  51. }