Home > Mobile >  Check for precision loss when converting string to float
Check for precision loss when converting string to float

Time:07-18

I have a string representing a rational number.

I want to convert the string to a float with strtof(nptr, &endptr)

The problem is that e.g. a string "1.0000000000000000000001" will be converted to 1. without raising any flags (iirc).

Therefore my question: How does one catch this precision loss?

CodePudding user response:

How does one catch this precision loss?

One doesn't, at least not with anything in the standard library; none of the strto* conversion functions will tell you if the value cannot be represented exactly.

Edit

I know that's not terribly helpful, but it means you'll have to go outside anything in the standard library. You'll either have to write your own conversion routines that somehow keep track of precision loss (I have no idea how you would implement this), or you'll have to go with some arbitrary-precision library like GMP, or you'll have to implement your own version of binary-coded decimal and hand-hack your own API to assign, compare, and manipulate BCD values.

C just doesn't give you the tools needed to do that kind of analysis.

  •  Tags:  
  • c
  • Related