Hello guys,
I am a little confused about the following. I need to get the number of floating digits of a float number. So I have for example the number:
12.345678
And I know that the number of int digits are 2 with the following code:
float a = 12.345678;
void setup()
{
int u=0;
while(a/pow(10.0,u)>1)
{
u++
}
print("nuber of units =",u);
}
void draw()
{
}
but when I want to count the number of decimals, I have witten this code:
void setup()
{
size(100,100);
println(numUnits(123.45678));
println(numDecimals(123.45678, 5));
}
void draw()
{
}
int numUnits(float a)
{
int u=0;
while(a/(pow(10.0,u))>1)
{
u++;
}
return u;
}
int numDecimals(float a, int limit)
{
int d=0;
float num=0;
float auxnum=a%numUnits(a);
float auxnum2=0;
//println(0-(a-(int)(a))*pow(10.0,1));
num = a-auxnum;//123.45678-123 -> 0.45678
println(num);
auxnum2=a-num;//123.45678-0.45678 -> 123.0
while(d<limit)
{
auxnum2=(auxnum2)*10;
auxnum2=(auxnum2)%1;
d++;
println("res:", d, "num", auxnum2);
}
return d;
}
The problem is that the print console shows the following:
3
123.0
res: 1 num 0.5677948
res: 2 num 0.677948
res: 3 num 0.77948
res: 4 num 0.7947998
res: 5 num 0.94799805
5
from that, I can take the first digit after the dot and I think this will get me back the digits of the float number, but I realize that those numbers are not correct, those should be something like:
res: 1 num 0.5678
res: 2 num 0.678
res: 3 num 0.78
res: 4 num 0.8
res: 5 num 0.0
Isn’t that correct?
But I dont know how to get that, I dont know if floating numbers get some errors when operating other numbers with them. So I wonder how can I get the number of digits without using number to string conversion techniques?
Many thanks in advance for any guidance