如何通过 JOptionPane 设置十进制数字输出的格式
我的作业要求我将值的格式设置为小数点后两位。我们被要求使用 JOptionPane 进行输入/输出。我知道如何使用 System.out.printf 将格式设置为两位小数。但是,我认为这行不通,因为我们需要使用 JOptionPane。
如果有人能给我任何关于如何将其格式化为字符串的建议(这样我就可以将字符串解析为双精度),我将不胜感激。谢谢。
这是我的代码如下:
package Program4;
import javax.swing.*;
public class Program4 {
public static void main (String[] args)
{
//Declaration of Variables
Double AssessedValue;
Double TaxableAmount;
Double PropertyTax;
Double TaxRatefor100 = 1.05;
String StrAssessedValue;
String OutputStr;
//Ask the user for the Assessed Value of their property
StrAssessedValue = JOptionPane.showInputDialog("Enter the assessed " +
"value of your property: ");
//Convert the string into a double
AssessedValue = Double.parseDouble(StrAssessedValue);
//Calculations
TaxableAmount = 0.92*AssessedValue;
PropertyTax = (TaxableAmount/100)*1.05;
//Store the output in a string
OutputStr = "Assessed Value: $" + AssessedValue + "\n" +
"Taxable Amount: $" + TaxableAmount + "\n" +
"Tax Rate for each $100.00: $" + TaxRatefor100 +
"\n" + "Property Tax: $" + PropertyTax;
//Output the result
JOptionPane.showMessageDialog(null, OutputStr, "Property Tax Values",
JOptionPane.WARNING_MESSAGE);
}
}
My assignment asks me to format values to two decimal places. We are asked to use the JOptionPane for input/output. I know how to format to two decimal places using the System.out.printf. However, I don't think that would work, because we need to use the JOptionPane.
If anyone could give me any advice on how to format it in a string (so I could then parse the string into a double), I'd appreciate it. Thanks.
Here is my code as follows:
package Program4;
import javax.swing.*;
public class Program4 {
public static void main (String[] args)
{
//Declaration of Variables
Double AssessedValue;
Double TaxableAmount;
Double PropertyTax;
Double TaxRatefor100 = 1.05;
String StrAssessedValue;
String OutputStr;
//Ask the user for the Assessed Value of their property
StrAssessedValue = JOptionPane.showInputDialog("Enter the assessed " +
"value of your property: ");
//Convert the string into a double
AssessedValue = Double.parseDouble(StrAssessedValue);
//Calculations
TaxableAmount = 0.92*AssessedValue;
PropertyTax = (TaxableAmount/100)*1.05;
//Store the output in a string
OutputStr = "Assessed Value: $" + AssessedValue + "\n" +
"Taxable Amount: $" + TaxableAmount + "\n" +
"Tax Rate for each $100.00: $" + TaxRatefor100 +
"\n" + "Property Tax: $" + PropertyTax;
//Output the result
JOptionPane.showMessageDialog(null, OutputStr, "Property Tax Values",
JOptionPane.WARNING_MESSAGE);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者
or
对于输入,您可以考虑使用
JSpinner
具有适当的SpinnerNumberModel
,或JFormattedTextField
。For the input, you might consider using a
JSpinner
with an appropriateSpinnerNumberModel
, or aJFormattedTextField
.