I have a library which needs to parse double numbers which always use a point '.' as decimal separator. Unfortunately for this case, strtod() respects the locale which might use a different separator and thus parsing can fail. I can't setlocale() - it isn't thread-safe. So I'm searching for a clean locale-independent strtod implementation now. I have found multiple implementations so far, but all of them look hacky or just like bad code. Can someone recommend a well-tested, working, clean (ANSI) C implementation for me?
相关问题
- Multiple sockets for clients to connect to
- how to split a list into a given number of sub-lis
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Generate string from integer with arbitrary base i
There's also gdtoa available on netlib, BSD style license: http://www.netlib.org/fp/gdtoa.tgz
Following the answer above, I tried using the Ruby implementation at ruby_1_8/missing/strtod.c. However, for some inputs this gives different answers to gcc's built-in parser and to strtod from stdlib.h, both on Mac and on Linux platforms:
which prints
So my advice is to test the chosen implementation before use.
Grab some known implementation (that doesn't depend on
atof
), such as the one distributed with ruby: ruby_1_8/missing/strtod.c.Warning: The proposed implementation from ruby contains bugs. I wouldn't mind the small difference pointed out by gavin, but if you try to parse something like "0.000000000000000000000000000000000000783475" you will get 0.0 instead of 7.834750e-37 (like the stock strtod() returns.)
Other solution:
I don't know how fast this is, though.