gpt4 book ai didi

java - Java中使用if语句时如何四舍五入小数?

转载 作者:行者123 更新时间:2023-12-01 21:16:50 27 4
gpt4 key购买 nike

我是 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

我认为因为利息是永远的小数,所以它把其他一切都搞砸了。我希望兴趣不是“0.49999999999”,而是“0.50”。预先非常感谢您提供的任何帮助。

最佳答案

String.format("%.2f", var); 其中var是你的newBalance等

四舍五入到小数点后两位。

查看https://www.dotnetperls.com/format-java获取格式化程序可以执行的操作的列表。

关于java - Java中使用if语句时如何四舍五入小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39885603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com