十进制值错误

时间:2015-02-11 02:15:00

标签: java

我正在编写一个程序,用于从用户那里获取2个输入:1)项目的价格2)支付的金额。然后它将返回两者的差异(更改到期),然后它将计算将返还多少票据和硬币。我在找到小数(准确地说是硬币值)时遇到了麻烦:

int one, five, ten, twenty,qs, ds, ns, ps, rem ;
    double price, pay,change;
    String user;
    Scanner input = new Scanner(System.in);
    do {
        System.out.print("Price: $");
        price = input.nextDouble();
        System.out.print("From: $");
        pay = input.nextDouble();
        change = pay - price;


        twenty =  (int) (change / 20.00);
        rem =  (int) (change % 20.00);
        ten =  (int) (rem / 10.00);
        rem =  (int) (rem % 10.00);
        five =  (int) (rem / 5.00);
        rem =  (int) (rem % 5.00);
        one =  (int) (rem);
        //
        qs = (int) rem / 25;
        rem = (int) rem % 25;
        ds = (int) rem / 10;
        rem = (int) rem % 10;
        ns = (int) rem / 5;
        rem = (int) rem % 5;
        ps = (int) rem;
        System.out.println("Computed change: $" + change);
        System.out.println(twenty + " x $20 bills, \n" + ten
                + " x $10 bills, \n" + five + " x $5 bills, \n" + one
                + " x $1 bills, \n" + qs + " x 25c coins \n" + ds
                + " x 10c coins \n" + ns + " x 5c coins \n" + ps
                + " x 1c coins \n");

        System.out.println("Would you like to enter another "
                + "quantity? (Y or N):");
        input.nextLine();
        user = input.nextLine();

        if (!user.equalsIgnoreCase("y")) {
            System.out.println("Goodbye!");
        }
    } while (user.equalsIgnoreCase("y"));
    input.close();
    // System.exit(0);

我几乎可以确定问题在于将余数的值转换为int,这将丢弃小数点后的任何值。我已尝试使用.25,.10,.5,.1进行dividng和modulo操作,但这似乎不起作用。有一些我没有看到的东西。

2 个答案:

答案 0 :(得分:1)

以美分计算价格,这样就可以避免使用小数位。

答案 1 :(得分:0)

您不应将doublefloat用于货币,因为它们的精确度并不完美。您可能希望将整个数字转换为表示美分的Long,然后格式化以输出小数。这样,你的数学微积分将是十进制的。

这样的东西
Long price = Long.parseLong(input.nextLine().replace(",", ""));
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
String s = n.format(price / 100.0);
System.out.println(s);

现在,您应该能够轻松解决您的问题。