Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: What is the portable/safe(thread aware) way to convert a number to a string w/o locale settings?

Tags:

c

locale

glibc

What is the safe/portable way to convert a number to a string (and the other way around) ?

I'm on Linux and my settings locale is so that when I use sprintf numbers have a "," instead of a "." as a separator.

Sometimes I want them that way, Sometimes not :)

I saw some solutions that imply playing with users settings. Clearly that's something one should not do. Somebody suggested using uselocale

snprintf : simple way to force . as radix?

can someone elaborate a bit (looks like it's buggy on some glibc (<2.12)) and if possible provide some sample code (eg a macro SNPRINTF_POSIX).

I tried myself but my C skills are very limited.

[edit]

I find this code by [GO]Skywalker13 on Swisslinux.org after writing my question. Any thoughts about it ? What about memory usage ? (I need to make numerous calls to this func)

#define _GNU_SOURCE
#include <locale.h>
#include <stdlib.h>

double
my_atof (const char *nptr)
{
  double res;
  locale_t new_locale;

  new_locale = newlocale (LC_NUMERIC_MASK, "C", NULL);
  res = strtod_l (nptr, NULL, new_locale);
  freelocale (new_locale);

  return res;
} 
like image 237
frenchone Avatar asked May 12 '11 15:05

frenchone


1 Answers

With POSIX 2008, you can use the newlocale and uselocale functions to temporarily change the locale in the current thread without affecting other threads. This is really the only solution, aside from never setting the LC_NUMERIC locale category to begin with. On the other hand, I prefer banning use of LC_NUMERIC in software I write, at least for the global locale. Then you can use newlocale and uselocale locally at the point where you want numeric formatting that matches your user's cultural conventions, and on systems that lack POSIX 2008 uselocale, simply leave out localized numeric printing.

like image 113
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 05:09

R.. GitHub STOP HELPING ICE