开发者

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

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;
} 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜