在Java中使用if语句时如何舍入小数?

时间:2016-10-06 00:17:13

标签: java if-statement

我是Java新手,我正在编写一个信用卡Java分配编码,您可以在其中向信用卡添加费用并添加利息。我使用If语句编写了一个兴趣,但它输出的是一个未舍入的小数。

public class Credit_Card
{
    public static void main (String []args)
    {
        Scanner c = new Scanner (System.in);
        double num1, num2, interest, newBalance, min = 0;

        int num3 = 50;

        System.out.println ("What is the previous balance?");
        num1 = c.nextInt();

        System.out.println ("What is the total amount of additional       charges?");
        num2 = c.nextInt();

        interest = num2;

        if (num2 == 0)
         interest = (interest + 0); //There is no interest if num2 is 0

        if (num2 > 0)
        interest = (interest*(2.0f/100.0f)); //total amount of money owed is multiplied by 2 percent

        newBalance = num1 + num2 + interest;

        System.out.println ("CS CARD International Statement");
        System.out.println ("===============================");
        System.out.println ("");
        System.out.println ("Previous Balance:      $" + num1 );
        System.out.println ("Additional Charges:    $" + num2 );
        System.out.println ("Interest:              $" + interest );
        System.out.println ("");
        System.out.println ("New Balance:           $" + newBalance);
        System.out.println ("");

        if (newBalance < 50)
         min = newBalance;

        if(newBalance >= 50 && newBalance <= 300)
         min = num3;

        if(newBalance > 301)
         min = (newBalance*(20.0f/100.0f));

        System.out.println ("Minimum Payment:       $" + min);
    }
}

输出如下:

What is the previous balance?
1000
What is the total amount of additional charges?
25
CS CARD International Statement
===============================

Previous Balance:      $1000.0
Additional Charges:    $25.0
Interest:              $0.4999999888241291

New Balance:           $1025.4999999888241

Minimum Payment:       $205.100003053993

我认为,因为兴趣是一个永恒的小数,它会搞砸其他一切。而不是兴趣&#34; 0.49999999999&#34;,我希望它喜欢&#34; 0.50&#34;。非常感谢您提前寻求帮助。

1 个答案:

答案 0 :(得分:3)

String.format ("%.2f", var);其中var是你的新平衡等等。

这将它舍入到小数点后两位。

查看https://www.dotnetperls.com/format-java,了解格式化程序的功能列表。