Basically I am changing layout ratios. I have to change current layout ratio to another ratio. There is a code snippet I am using in my application.
import java.util.*;
public class Big{
public static void main(String args[]){
float b=(new Scanner(System.in)).nextFloat();
float a=(b*((float)225/440));
//Another layout ratio height
System.out.println(a);
//Back to previous layout height
float c=(a*((float)440/225));
System.out.println(c);
}
}
Below are some input and their respected outputs:
On input value- 50,60.0,65 and 69.9999, Code is returning same outputs-50,60.0,65 and 69.9999 respectively. But when I am trying to put 70 and 80, Code is returning approximate values as 69.99999 and 79.99999 respectively. The question is- Why am I getting these approximate value not exact values in case of 70 and 80. There can be some other cases. I am trying to get exact values in all the cases.
Use BigDecimal for exact calculations, although be careful because is REALLY slow.
As the comments on top say, floating type math is unexact by design: there is no way to represent the infinity of numbers that can be created in the set of real numbers
BigDecimal exists for these kind of calculations. But it trades preciseness for speed.