Jump to content
  • Advertisement
Sign in to follow this  
XeonXT

Convert Float to Char Array

This topic is 2804 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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?

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!