Sign in to follow this  
XeonXT

Convert Float to Char Array

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this