I have been trying to make a program to round doubles after decimal point- for example-4.45 will turn 4.50 and 3.23-3.20 and so on.
for that I have tried to count how many numbers are after the decimal point them multiply it by 10 powered that number that I found add or deduct accordingly to make it round as a whole integer-for example 4.45 will first turn 445 then 450 then I divide it again by that number I found so I will end up with 4.50.
what I did technically works, only problem I have is with counting the number of digits after the decimal point. for example I entered 20.13 as my double and I tried multiplying it by 10 until it is equal it's int-like if 201.3==201 otherwise I keep multiplying by 10. Only problem is it ruins my numbers in debug I saw it turned 20.13 to 201.299999998 instead of 201.3 and that makes my loop basically infinite and defeats the purpose altogether.
my function :
//input : The function gets a double number
//output : The function returns how many numbers are after the decimal point
public static int countDecimal(double num){
int count=0;
while(num!=(int)num){
num*=10;
count++;
}
return count;
}
Does anyone know why it's doing that and how do I achieve my purpose? I would also love to know if you know an easier way to round 4.45 to 4.5 because my way requires many other functions and is pretty long for something rather basic. The java function I saw only rounds to integers-4.5 to 5 for example.