I have float number in char[]. It’s DE or PL localized string, and has ',' not '.' as decimal separator. Is there any standard way to convert such string to float? I’m looking for something better then “replace , with . and use atoi“.
I have float number in char[] . It’s DE or PL localized string, and
Share
As @Omkant suggested,
strtod()will do for you:You can use a NULL instead of &endPtr, and if you are sure that you’ll never attempt to convert zeroes, you can use
valbeing zero to check for errors instead of settingerrno:In some contexts the slightly more expensive sscanf will be better, because
strtodcan accept alternative number formats such as hexadecimal. In some cases you might not want to allow something that’s not a “proper” float, e.g. 3.14159, to make it past the conversions stage;strtod()will allow it.Also,
strtod()will accept (and in the sloppier version, not detect) strings such as “INFERIOR” (which will be interpreted as INFinity with a tail of ERIOR). Not really likely, but in some contexts it could lead to an application vulnerability if the value is under the user’s control.