双倍显示很长的数字 [英] double displaying very long number

查看:210
本文介绍了双倍显示很长的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的计算,使用双打,但我得到一个意想不到的结果,我不明白为什么?

I have a simple calculation that uses doubles but I'm getting an unexpected result and I can't understand why?

import java.util.Scanner;
public class VersatileSnitSoft {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);
        double amount;
        System.out.print("What’s the price of a CD-ROM? ");
        amount = myScanner.nextDouble();
        amount = amount + 25.00;
        System.out.print("We will bill $");
        System.out.print(amount); 
        System.out.println(" to your credit card.");

    }

}

如果我输入2.99我得到的结果是..

If I enter 2.99 the result I get is..

We will bill $27.990000000000002 to your credit card.


推荐答案

在双打操作时,不能精确表示小数值(或漂浮)。
使用 BigDecimal 代替。

You cannot represent decimal values precisely whilst operating on doubles (or floats). Use BigDecimal instead.

编辑(2)

此处示例:

BigDecimal amount = new BigDecimal("2.99");
amount = amount.add(new BigDecimal("25.00"));
System.out.println(amount.toString());

输出:

27.99

这篇关于双倍显示很长的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆