EDIT: Someone marked this question as a duplicate of the typical "Why does 0.1 + 0.3
return 0.40000000001
?", but please notice I'm not asking why this happens; I'm fully aware of it. I just want to know if there is a workaround in cases like the following, when rounding isn't an option.
When writing the following noDigits
function, that is supposed to return the number of digits of an integer n
given a certain base
,
#include <math.h>
using namespace std;
int noDigits(int n, int base = 10) {
return (n != 0) ? int(floor(log(abs(n)) / log(base)) + 1) : 1;
}
I ran into the following precision problem: if I print out log(abs(1000))/log(10)
I get 3
, but when I apply floor
to that (i.e. floor(log(abs(1000))/log(10))
), I get 2
.
I guess it is due to log(abs(1000))/log(10)
being stored as something like 2.9999999[...]
, but I'm not sure how to solve it; there are cases in which log(abs(n))/log(base)
will actually be something like 2.9987456[...]
, so rounding to a certain precision is not an option.
How can I overcome this?
Clarification: while there are many simple alternatives for solving this particular problem, I'm asking if there's a general workaround for working with floor
(or int
conversion)—which there doesn't seem to be.