gpt4 book ai didi

java - 如何在 Java 中对用户输入进行四舍五入

转载 作者:行者123 更新时间:2023-12-01 20:18:07 24 4
gpt4 key购买 nike

我正在尝试获取用户输入的小数,然后将其四舍五入到小数点后两位。这是我目前无法正常工作的代码,我不知道为什么。

package code;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalPlaces {

public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
Scanner qweInput = new Scanner(System.in);
System.out.println("Enter a decimal number:");
String qwe1 = qweInput.next();
df.format(qwe1);
System.out.println(qwe1);
}

}

最佳答案

使用扫描仪时,最好使用 nextLine()(如果可以的话),它可以防止返回行字符出现错误:

String qwe1 = qweInput.nextLine();

然后您需要解析为 double,因为如果不是,它会尝试从 Object 转换为 double 并且崩溃

df.format(Double.parseDouble(qwe1));

然后format方法返回字符串formated,因为String是不可变的,所以你需要直接打印或保存它:

qwe1 = df.format(Double.parseDouble(qwe1));
System.out.println(qwe1);
//----------------------------------OR----------------------------------
System.out.println(df.format(Double.parseDouble(qwe1)));
<小时/>

编辑:为了避免解析为Double,您可以使用Scanner中的nextDouble(),因为它会直接保存为 double ,但要保存格式,您需要另一个字符串,因此具有正确的名称;)

关于java - 如何在 Java 中对用户输入进行四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45376534/

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