In a solution to an exercise in the Book Art and Science of Java I had to write a program that converts Kilograms into the corresponding values in Pounds and Ounces. I wrote the program but when I try to convert say 1kg, the result the program gives me is: 1 kg = 2 pounds and 3.200000000000006 ounces
Now my constants are 2.2 pounds per kg and 16 ounces per pound so 3.2 ounces is correct. But not with so many 0's and that 6 at the end freaks me out.
Anyone know why this happens and how it can be solved? Thank you!
Here's the code:
/*
* File: KgsLibras.java
* Program that converts kilograms in pounds and ounces.
*/
import acm.program.*;
public class KgsLibras extends ConsoleProgram {
public void run () {
println ("This program will convert kilograms in pounds and ounces");
double kgs = readDouble ("Insert kgs value: ");
double libras = kgs * LIBRAS_POR_KG;
double oncas = (libras - (int)libras) * ONCAS_POR_LIBRA;
println ((int)libras + " libras" + " e " + oncas + " Onças.");
}
private static final double LIBRAS_POR_KG = 2.2;
private static final int ONCAS_POR_LIBRA = 16;
}