double
has more accuracy of precision that float
but still has rounding errors. You have to round any answer you get to have a sane output.
If this is not desireable you can use BigDecimal which does not have rounding errors, but has its own headaches IMHO.
The default Float.toString() uses minimal rounding, but often its not enough.
System.out.println("With no rounding");
double n = 5.3d;
System.out.println("n= "+new BigDecimal(n));
double expected = 0.3d;
System.out.println("expected= "+new BigDecimal(expected));
System.out.println("n % 1= "+new BigDecimal(n % 1));
System.out.println("n - Math.floor(n) = "+new BigDecimal(n - Math.floor(n)));
System.out.println("n - (int)n= "+new BigDecimal(n - (int)n));
System.out.println("With rounding");
System.out.printf("n %% 1= %.2f%n", n % 1);
System.out.printf("n - Math.floor(n) = %.2f%n", n - Math.floor(n));
System.out.printf("n - (int)n= %.2f%n", n - (int)n);
Prints
With no rounding
n= 5.29999999999999982236431605997495353221893310546875
expected= 0.299999999999999988897769753748434595763683319091796875
n % 1= 0.29999999999999982236431605997495353221893310546875
n - Math.floor(n) = 0.29999999999999982236431605997495353221893310546875
n - (int)n= 0.29999999999999982236431605997495353221893310546875
With rounding
n % 1= 0.30
n - Math.floor(n) = 0.30
n - (int)n= 0.30
A bit of a googling might have helped : https://stackoverflow.com/a/5017110/820410