CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: how to determine how many digits there are in a number after the decimal point?

1. Member
Join Date
Aug 2002
Posts
44

## how to determine how many digits there are in a number after the decimal point?

hi,

so I'd like to determine how many digits a number has after the decimal point.

For example:
2.300000 => one digit
0.00040 => four digits
232.4343003 => seven digits
1214 => zero digits

thanx,

Usul

2. ## Re: how to determine how many digits there are in a number after the decimal point?

If the numbers are floating point (double or float), then this doesn't quite make sense. If you are working with some exact rational number package, then it may make sense.

Why do you need to do this?

3. Member
Join Date
Aug 2002
Posts
44

## Re: how to determine how many digits there are in a number after the decimal point?

Im using double. Its hard to explain what I need it for, but it doenst matter anyway. I think the problem is clear.

I need a function:
int getDigitsAfterDecimalPoint(double number)

4. Member
Join Date
Jul 2002
Location
Boston, MA
Posts
335

## Re: how to determine how many digits there are in a number after the decimal point?

here is the first thing that pops into my mind (you may be outraged by this solution but it works ) Convert it to string and see how many character you have after the dot.

5. Senior Member
Join Date
Apr 2004
Location
Posts
1,342

## Re: how to determine how many digits there are in a number after the decimal point?

I agree with gradiov. Just to expand on his solution:

1) The simplest way to convert a double to a string is with stringstream, found in the <sstream> header.

2) Be aware that floating-point numbers only have a certain amount of precision (usually 15 digits for double, 18 for long double), so if you're handling numbers that require more than this many digits, floating-point is not your answer. Also, to make sure the double is outputted into the stringstream with maximum precision, use

stream.precision(x);

where stream is your stringstream object, and x is the maximum precision for the floating-point type you use.

6. ## Re: how to determine how many digits there are in a number after the decimal point?

Hmm, theoretically the following apporach could work:
Code:
```#include <cmath>
unsigned int getDigitsAfterDecimalPoint(double number)
{
unsigned int retval = 0;
int pow = 1;
double tmp;

while ( true ) {
tmp = trunc(number * pow)/pow;
if ( tmp == number ) return retval;
++retval;
pow *= 10;
}
}```
But I really would not put that into any program (it will certainly end up some time in an endless loop) but agree with the two previous posters that using strings is the way to go. Here is why:

The way processors handle floating point numbers is different from the way humans do (most humans, granted). Thus, the concept of significant digits after the floating point exists in the human world, but not in the micro-processor world. So to determine the number of digits, you have to convert the float from the processor world into human world. Which means to convert it into a string.

PS: I wish C++ would throw an exception if the pow*=10 operation failed.

7. mop
Member
Join Date
Jun 2001
Location
Orlando, FL
Posts
232

## Re: how to determine how many digits there are in a number after the decimal point?

To further expand on gradiov point.

The Boost-people have a nice solution (http://www.boost.org) called
lexical_cast. Here's a short version:

Code:
```#include <strstream>
#include <typeinfo>

namespace boost
{
template<typename T, typename S> T lexical_cast(const S& arg)
{
std::strstream interpreter;
T result;

if(!(interpreter << arg) || !(interpreter >> result) ||
!(interpreter >> std::ws).eof())

return result;
}
}

lexical_cast like this:

#include <iostream>
#include <string>
#include <boost/lexical_cast.h> // Or something similar...

std::string doubleToString( const double d )
{
std::string result = boost::lexical_cast< string >( d );
if( result.find( '.' ) == std::string::npos ) result += ".0";
return result;
}

int main()
{
std::cout << doubleToString( 0.0 ) << endl;
std::cout << doubleToString( 0.1 ) << endl;
std::cout << doubleToString( 1.0 ) << endl;
std::cout << doubleToString( 1.01 ) << endl;

return 0;
}```

8. ## Re: how to determine how many digits there are in a number after the decimal point?

Ok, I wasn't clear enough in my post. The problem is that:

a) floating point numbers are stored in binary and not in decimal. So whereas you can represent 0.1 exactly as a decimal fraction, you can't do this in binary. So the binary expansion doesn't have 1 or 2 decimal places, but an infinite expansion. You will run into this a lot.

b) Because floating point arithmetic is only approximate, you can end up with situations where you add two numbers with 2 decimal places and get a number with more.

For an easy example, check what the following program gives you:
Code:
```#include <stdio.h>

int main()
{
printf("%0.15f", 232.4343003);
return 0;
}```
At least on my computer it gives 232.434300299999990.

While the conversion routines from floating point to decimal and back are pretty good, you are bound to run into trouble like this.

9. Member
Join Date
Jul 2002
Location
Boston, MA
Posts
335

## Re: how to determine how many digits there are in a number after the decimal point?

Totally agree with Yves M but since "problem is clear" to the person who asks the question, all we have to do is put our .02\$ in.

10. Member
Join Date
Jan 2004
Posts
131

## Re: how to determine how many digits there are in a number after the decimal point?

The logic behind this is simple, yet it may be difficult for someone with little experience to implement.

Let me see if I've got this right: you wanna count the length of the number of nonzero digits, so to speak, beyond the decimal point, correct?

So, a number that has a lot of trailing zeroes at the end, like "1.020500000" would be four, for "1.0205", correct?

Populate an array with the individual decimal integers one by one, then iterate through the array, updating a temporary variable with the current index of the array if it holds a non-zero integer. Add 1 to that counter and that should tell you how many "significant" decimal places you have.

The array is only a suggestion. The basic idea is to have a counter that is updated with the index of the iterator as you iterate through the number/string/array/decimal points each time you encounter a non-zero digit. That way, you'll have the last index of a non-zero integer, giving you the number of "significant digits" (for lack of a better word...).

Hope that helps!

11. _uj
Banned
Join Date
Nov 2003
Posts
1,405

## Re: how to determine how many digits there are in a number after the decimal point?

[QUOTE=Yves M]Ok, I wasn't clear enough in my post. The problem is that:

a) floating point numbers are stored in binary and not in decimal. ..............

b) Because floating point arithmetic is only approximate, .................
[/code]

This fundamental problem (that a number which has an exact representation in one number system seldom has it in another) can be made to disappears.

It does if the proposed algoritm is defined in the domain of decimal numbers. This means that the rounding errors introduced by the conversion back and forth between decimal and binary can be made to go away. And it will if the decimal representation is always rounded to a specific number of significant digits.

So the proposed algoritm (using a decimal string representation) is correct if rounding is also well defined. Theoretically you've sought a solution at a coarser level und thus got rid of the unwanted "fuzziness" of lower levels. This is often done in physics for example.

12. Member
Join Date
Aug 2002
Posts
44

## Re: how to determine how many digits there are in a number after the decimal point?

thanx.

Im going to try that String-approach.

By the way: I dont have numbers with more then 15 digits. Only relativly small numbers (or I dont care for greater precision).

And Im not counting the non-zeros after the decimal-point, because myfunction(0.00001) = 5 , for example. I want to have the number of valid digits.

I hope I'll find out how to convert double to String without preceding zeros, but I'll try for myself.

thanx,

Usul

13. Member
Join Date
Aug 2002
Posts
44

## Re: how to determine how many digits there are in a number after the decimal point?

ok, this works (if you are interested)

Code:
```int CChipzahlDoc::getValidDigits(double number)
{
char buffer[100];

sprintf(buffer, "%f", number);

int helpInt = 0;
int ret = 0;
bool afterComma = FALSE;
while( buffer[helpInt] != '\0' )
{
if( afterComma )
{
ret++;
}

if( buffer[helpInt] == '.' )
{
afterComma = TRUE;
}

helpInt++;
}
helpInt--;
while( helpInt > 0 )
{
if( buffer[helpInt] == '0' )
{
ret--;
}
else
{
break;
}
helpInt--;
}

return ret;
}```

14. Member
Join Date
May 2004
Posts
45

## Re: how to determine how many digits there are in a number after the decimal point?

Originally Posted by Usul
I'd like to determine how many digits a number has after the decimal point.

For example:
2.300000 => one digit
0.00040 => four digits
232.4343003 => seven digits
1214 => zero digits
1/3 will give theoretically 0.333333333333.... so your question is not easy to answer. In practice 1.0 / 3.0 will give a finite floating-point number that is very close to 1/3 but is not mathematically equal to 1/3.

15. Member
Join Date
Aug 2002
Posts
44

## Re: how to determine how many digits there are in a number after the decimal point?

Yes, but as I mentioned before I do not care for precision.

Just pretend my numbers dont have more then 10 digits after the decimal point.
For example I could do this: number = (double)((int)(number*10000000000))/10000000000;

But hey, I solved it and it works.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•