java 如何通过 JOptionPane 格式化十进制数的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7772195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How format the output of decimal numbers via the JOptionPane
提问by sbman12
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.
我的作业要求我将值格式化为两位小数。我们被要求使用 JOptionPane 进行输入/输出。我知道如何使用 System.out.printf 将格式设置为两位小数。但是,我认为这行不通,因为我们需要使用 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 0.00: $" + TaxRatefor100 +
"\n" + "Property Tax: $" + PropertyTax;
//Output the result
JOptionPane.showMessageDialog(null, OutputStr, "Property Tax Values",
JOptionPane.WARNING_MESSAGE);
}
}
回答by mKorbel
String.format("%.2f", myNumber);
or
或者
DecimalFormat decFormat = new DecimalFormat("0.00");
回答by Andrew Thompson
For the input,you might consider using a JSpinner
with an appropriate SpinnerNumberModel
, or a JFormattedTextField
.
对于输入,您可以考虑将 aJSpinner
与适当的SpinnerNumberModel
或 a 一起使用JFormattedTextField
。