Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Why in this Java program the Doubles in a String Output have too many decimals?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's just a consequence of how floating point works - literally thousands of other references to these issues here on SO alone. The short version is that not all numbers can be represented exactly using floating point numbers, which leads to oddities like the one you're seeing. This document should teach you all you should know about floating point.

In the mean time you can use format to get printf-like formatting options:

System.out.format ("%.0f libras e %.2f On?as.
",libras,oncas);

or if you have to use that specific println method, use String's format:

println(String.format ("%.0f libras e %.2f On?as.",libras,oncas) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...