**0**

# Getting number of significant digits in float

###
#1
Crossbones+ - Reputation: **3097**

Posted 04 May 2012 - 07:49 PM

###
#2
Moderators - Reputation: **21042**

Posted 04 May 2012 - 08:35 PM

For base 2, yes, you can tell how many significant digits are present trivially: there are 23 in single precision IEEE floats, and 52 in double-precision. You can use simple bit-counting algorithms to count how many of them are relevant in a particular value.

For base 10... well, not really. You have to convert the fraction to base 10 to know how many significant digits it represents (if it can even represent the base 10 value precisely!) at which point you've basically done a string format anyways.

**Edited by ApochPiQ, 04 May 2012 - 08:36 PM.**

###
#3
Crossbones+ - Reputation: **3097**

Posted 04 May 2012 - 10:08 PM

###
#4
Members - Reputation: **2143**

Posted 05 May 2012 - 01:48 AM

For base 2, yes, you can tell how many significant digits are present trivially: there are 23 in single precision IEEE floats, and 52 in double-precision. You can use simple bit-counting algorithms to count how many of them are relevant in a particular value.

Ignoring denormalized floats, I think there's 24 bits of precision, since there's an implicit leading one that is not stored.

That aside, Bruce Dawson digs into floats in a very nice manner, and has got a blog post about float precision in base 10. The TL;DR simplified answer is "... range from 6-9 decimal digits" and "Use 9 to play it safe."

###
#5
Crossbones+ - Reputation: **3097**

Posted 05 May 2012 - 09:52 AM

...

Ignoring denormalized floats, I think there's 24 bits of precision, since there's an implicit leading one that is not stored.

That aside, Bruce Dawson digs into floats in a very nice manner, and has got a blog post about float precision in base 10. The TL;DR simplified answer is "... range from 6-9 decimal digits" and "Use 9 to play it safe."

Right, I know the maximum decimal precision for a given float. I am looking for the number of significant digits in any given float. 1.0 would be one, 12321.4535 would be nine, 0.145 would be three, etc.

###
#6
Moderators - Reputation: **40171**

Posted 05 May 2012 - 10:07 PM

That is the best precision that you can convert to decimal digits and back without loss.

Otherwise, the answer is that you ALWAYS have 23 bits of precision. The FPU doesn't arbitrarily stop midway, it carries out the entire operation.

If you want to keep track of how much of that answer you care about, you'll need to track it on your own in some other variable.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I occasionally write about assorted stuff.