string2float

E

Eric Sosman

Chris said:

strtod() is better, but neither actually converts a
string to float: both convert to double. The only way I
can think of to convert directly to float is

if (sscanf(my_string, "%f", &float_variable) == 1)
 
F

Flash Gordon

Chris said:

Not a very good choice. You can't test to see if it worked and if the
value cannot be represented as a double it invokes undefined behaviour
(i.e. anything can happen). A far better function to use is strtod. This
allows you to test how much of the string was converted and if it is out
of range behave in a defined manner including setting errno, and thus
you can do error checking reliable and report problems such as the user
entering "fiftythree" of "12e456789".
 
R

Robert Gamble

Eric said:
strtod() is better, but neither actually converts a
string to float: both convert to double. The only way I
can think of to convert directly to float is

if (sscanf(my_string, "%f", &float_variable) == 1)

C99 has strtof() which will convert directly to float representation.

Robert Gamble
 
K

Keith Thompson

Robert Gamble said:
C99 has strtof() which will convert directly to float representation.

And if your implementation doesn't have strtof(), it's easy enough to
call strtod() and assign the result to a float. It's even easier to
use double in the first place.

sscanf() has the disadvantage that, if the floating-point literal in
the string represents a value that can't be represented in the target
type, the behavior is undefined. strtod() has well-defined behavior
on overflow. (It would have been nice if sscanf() had been defined
this way as well.)
 
R

Robert Gamble

Keith said:
And if your implementation doesn't have strtof(), it's easy enough to
call strtod() and assign the result to a float.

Except that if the result can be represented as a double but is outside
the range of float then assigning the return value to a float will
result in undefined behavior. In this case one would need to check the
return value of strtod before assigning it to float, which is a pain
and probably why strtof() was added.
It's even easier to use double in the first place.
Agreed.

sscanf() has the disadvantage that, if the floating-point literal in
the string represents a value that can't be represented in the target
type, the behavior is undefined. strtod() has well-defined behavior
on overflow. (It would have been nice if sscanf() had been defined
this way as well.)

Robert Gamble
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top