【问题标题】:How format the output of decimal numbers via the JOptionPane如何通过 JOptionPane 格式化十进制数的输出
【发布时间】:2011-10-14 18:51:15
【问题描述】:

我的作业要求我将值格式化为小数点后两位。我们被要求使用 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);           
        }
}

【问题讨论】:

    标签: java swing joptionpane number-formatting


    【解决方案1】:
    String.format("%.2f", myNumber);
    

    DecimalFormat decFormat = new DecimalFormat("0.00");
    

    【讨论】:

      【解决方案2】:

      对于输入,您可以考虑使用JSpinner 和适当的SpinnerNumberModel,或JFormattedTextField

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 2011-04-19
        • 2013-01-23
        • 2020-07-21
        • 1970-01-01
        相关资源
        最近更新 更多