【问题标题】:Java: adding floating point numbers with expansionsJava:使用扩展添加浮点数
【发布时间】:2013-08-08 19:34:16
【问题描述】:

如果有人问到这个问题,我深表歉意,但我找不到任何可以帮助我的东西。当我想添加数字并显示它们时,这是我较大程序的一部分,但是当我遇到数字 0.6 时,输出不“准确”。我想将它们精确显示到小数点后一位。我怎样才能做到这一点?

源代码:

public class NumberTest {

    public static void main(String[] args){
        double n = 0.6;
        double sum = 0.0;
        for(int i = 0; i < 10; i++){
            System.out.println(sum);
            sum += n;
        }
    }
}

输出:

0.0
0.6
1.2
1.7999999999999998
2.4
3.0
3.6
4.2
4.8
5.3999999999999995

【问题讨论】:

    标签: java floating-point add


    【解决方案1】:

    不要使用 println 而是使用 printf(...),因为 printf 允许 格式化 输出。

    System.out.printf("%.1f%n", sum);
    

    或者使用 DecimalFormat 对象:

    DecimalFormat df = new DecimalFormat("0.0");
    
    System.out.println(df.format(sum));
    

    是的,这是一个重复的重复问题......

    【讨论】:

    • +1 我确信它与 Java 之前的语言重复。
    • @PeterLawrey:谢谢。我正在尝试找到最好的副本,因为这个问题确实应该被关闭,并且应该有一个指向具有适当接受答案的副本的链接。如您所知,其中大部分是从 C 借来的(它是从...借来的?)
    • @PeterLawrey:这是一个很好的相关问题:how-to-get-the-decimal-part-of-a-float。 1+回答!
    猜你喜欢
    • 2020-07-09
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2012-04-26
    相关资源
    最近更新 更多