[Haskell-cafe] How to calculate de number of digits of an integer?
(was: Is logBase right?)
Roberto López
plastermoso at hotmail.com
Sat Aug 22 13:19:26 EDT 2009
Ok. I wonder if someone could help me with this problem...
I want to calculate the number of digits of a positive integer. I was
thinking of ...
numDigits n = truncate (logBase 10 n) + 1
But (logBase 10 1000) = 2.9999999999999996 so numDigits 1000 = 2.
Maybe adding a small amount
numDigits n = truncate ((logBase 10 n) + 0.0000000000000005) + 1
Prelude> numDigits 100
3
Prelude> numDigits 1000
4
Prelude> numDigits 10000
5
Prelude> numDigits 10000
5
Prelude> numDigits 100000
6
Prelude> numDigits 1000000
7
Prelude> numDigits 10000000
8
Prelude> numDigits 100000000
9
Prelude> numDigits 1000000000
9 <---- This is wrong!!!!
Prelude> numDigits 10000000000
11
Is there a reliable way to calculate the number of digits by means of
logBase?
Regards!
More information about the Haskell-Cafe
mailing list