Calculating number of digits?
Hello all, I've ran into a problem in my programming recently.
How do I calculate the number of digits in a double variable? For example, for a double with the value of 93938, I want it to return a value of 5, meaning 5 digits. Is there any inbuilt functions which returns the number of digits of a double variable or do I have to code it myself?
Thanks for the help!
Re: Calculating number of digits?
You can use sprintf to write the number to a string and then get the length of the string :)
Re: Calculating number of digits?
For an integer :
Code:
int digits (T f)
{
return (1+floor(log10(abs(x)))));
}
For floats, I will use some form of sprintf, excepting the point or comma.
Re: Calculating number of digits?
Quote:
Originally Posted by indiocolifa
For a number (base 10) e.g:
Code:
int digits (T f)
{
return (1+floor(log10(abs(x)))));
}
T can be double, float, int ,etc... just overload it as you want.
Wicked! You need to be mathematician, a computer scientist like me can't understand that code.
Re: Calculating number of digits?
or a 'brute force' method - use integer division, and divide by multiples of 10 until the result is zero - would be a simple loop to write:
(int)(93938/ (1*10)) = 9394
(int)(93938/ (2*10)) = 940
(int)(93938/ (3*10)) = 94
(int)(93938/ (4*10)) = 9
(int)(93938/ (5*10)) = 0 // answer is 5
Re: Calculating number of digits?
indiocolifas solution will work, but it will only return the length of the numbers integral part.
- petter
Re: Calculating number of digits?
Quote:
Originally Posted by wildfrog
indiocolifas solution will work, but it will only return the length of the numbers integral part.
- petter
Exactly petter, I modified the post to point that. It's for integers.
For floats, may be a good math solution (not sprintf "hacks" :D ) is to iterate like ghovis proposed.
Re: Calculating number of digits?
As noted, these solutions are good for integers, but all of them will have problems with a double (or float).
Printing to a string depends on the format used to print - any many doubles/floats cannot be represented exactly, so the number of digits would be infinite.
To make indiocolifa's solution a bit more generic, the number of digits required to represent a number is any number system (binary, octal, decimal, hex, etc), you can use
Code:
int digits (T f)
{
return (1+(floor(log10(abs(x)) / log10(base))));
}
Hope that helps.