Convert Float to Char Array

Started by
3 comments, last by Erik Rufelt 13 years, 5 months ago
Before you read further - I am NOT asking how to convert from a float to a string. I know how to do that.

I am building a custom string class and would like to implement a float-to-string conversion. How is this done manually? I'm not talking about sprintf or sstream or any other std:: workaround, I'm talking about the raw algorithm for manipulating a float to get a sequence of characters representing the digits of the float.

For example, with an integer, you would simply add char(integer%10 + '0') to a queue of digits, then integer/=10 and repeat. This would give you each digit as a char individually. How can this be done with a float?

Thanks :)
Advertisement
It depends on how you want to format it. How many decimal places or significant figures do you want? Scientific notation, or not, or only sometimes?
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Read the IEEE 754 floating point standard.

It sounds like you are doing this for the sake of doing this. Building a custom string class (unnecessary in itself usually) does not require hand implementing such a function.
It's not easy to implement correctly and efficiently. Excel 2007 had a well known bug caused by broken double to string conversion code.

However to get a simple bit of display code working, try taking the log to the base 10 of the floating point number (rounded up) to work out where to start, and then use repeated division by 10 from there. You probably only want to display up to about 6-8 digits for floats as any more than that aren't accurately stored.

This probably won't be as accurate as the standard library functions, thanks to division by 10 not being completely accurate, but it won't be too far off.

You'll also need to special case NaNs and Infinities.
http://en.wikipedia.org/wiki/Single_precision lists an example of how to convert to decimal.

This topic is closed to new replies.

Advertisement