GigaWatts
GigaWatts

Reputation: 123

strtof() function misplacing decimal place

I have a string "1613894376.500012077" and I want to use strtof in order to convert to floating point 1613894376.500012077. The problem is when I use strtof I get the following result with the decimal misplaced 1.61389e+09. Please help me determine how to use strof properly.

Upvotes: 1

Views: 546

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12668

The number 1613894376.500012077 is equivalent (the same number up to the precision of the machine as 1.61389e+09.) The e+09 suffix means that the decimal point is located nine decimal digits right the place it has been placed (or that the number is multiplied by 10 to the ninth power). This is a common notation in computer science called scientific notation.

Upvotes: 0

chux
chux

Reputation: 153592

A typical float is 32-bit and can only represent exactly about 232 different values. "1613894376.500012077" is not one of those.

"1.61389e+09" is the same value as "1613890000.0" and represents a close value that float can represent.

The 2 closest floats are:

1613894272.0 
1613894400.0 // slightly closer to 1613894376.500012077

Print with more precision to see more digits.

Upvotes: 4

Eric Postpischil
Eric Postpischil

Reputation: 222932

The decimal point is not misplaced. The notation “1.61389e+09” means 1.61389•109, which is 1,613,890,000., which has the decimal point in the correct place.

The actual result of strtof in your computer is probably 1,613,894,400. This is the closest value to 1613894376.500012077 that the IEEE-754 binary32 (“single”) format can represent, and that is the format commonly used for float. When you print it with %g, the default is to use just six significant digits. To see it with more precision, print it with %.999g.

Upvotes: 1

Related Questions