gpt4 book ai didi

java - 使用 GUI 输出框四舍五入到不同的小数位

转载 作者:行者123 更新时间:2023-12-01 18:35:43 30 4
gpt4 key购买 nike

我知道这是一项简单的任务,但我认为我只是在格式化方面遇到了问题。我可以让 GUI 输入框询问小数点后 8 位的数字,但对于输出框,我不知道如何将用户输入的数字四舍五入到小数点后 5 位和小数点后 3 位。这就是我所坚持的:

import javax.swing.JOptionPane;

public class Ch3Assignment6 {

public static void main(String[] args) {

String Decimal_Eight = JOptionPane.showInputDialog ("Enter a decimal number with eight decimal places");


JOptionPane.showMessageDialog (null,
"The number you entered is: " + Decimal_Eight + "\n" +
"The number rounded to 5 decimal places is: " + String.format("%.5f", Decimal_Eight) + "\n" +
"The number rounded to 3 decimal places is: " + String.format("%.3f", Decimal_Eight));

}

}

它显示错误消息/无输出消息框,但我不知道如何错误地输入舍入部分。谢谢!

最佳答案

您应用的字符串格式适用于浮点,而不适用于字符串。首先尝试将其解析为 double :

String input = JOptionPane.showInputDialog("Enter a decimal number with eight decimal places");
double Decimal_Eight = Double.parseDouble(input);

关于java - 使用 GUI 输出框四舍五入到不同的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22134783/

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