Writing your own float parser

I am trying to write a parser in C, and part of his job is to convert a sequence of characters to double. So far I have used strtod, but I believe this is quite dangerous and it will not handle cases where the number is at the end of the buffer, which is not terminated by zero.

I thought I would write it myself. If I have a string representation of a number of the form ab, I won’t think that I can just calculate (double) a + ((double) b / (double) 10 ^ n), where n is the number of digits in b?

For example, 23.4563:

a = 23 b = 4563

final answer: 23 + (4563/10000)

Or could this lead to inaccurate results regarding the IEEE float format?

+4
source share
3 answers

It is difficult to accurately read floating point numbers, in the sense that there are various problems that need to be carefully resolved, and many people do not. However, this is a problem. To get started, check out this article .

I agree with Roddy, most likely, you better not copy the data to the buffer and use the existing library functions. (However, you must make sure that your C implementation provides the correct rounded conversion of floating point numbers. The C standard does not require this, and some implementations do not provide it.)

+3
source

You may be interested in my answer to a somewhat related question .

The parser in this answer converts decimal floating-point numbers (represented as strings) into IEEE-754 floats and doubles them with the correct rounding.

As far as I remember, the only problem in the code is that it may not handle cases where the part of the exponent is too large (does not fit into an integer) and should equal the return of either an error or INF .

Otherwise, this should give you a good idea of ​​what to do (if you have an idea at all about what you are doing :).

+1
source

As already mentioned, this is difficult, you need extra accuracy, etc.

But if you have limited inputs and want to know if you can still correctly convert these limited decimal numbers to binary with a semi-naive algorithm and standard IEEE 754 ops, you might be interested in my answer to

How to manually parse a floating point number from a string

+1
source

All Articles