开发者

How format the output of decimal numbers via the JOptionPane

开发者 https://www.devze.com 2023-04-13 07:07 出处:网络
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 d

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);           
        }
}


String.format("%.2f", myNumber);

or

DecimalFormat decFormat = new DecimalFormat("0.00");


For the input, you might consider using a JSpinner with an appropriate SpinnerNumberModel, or a JFormattedTextField.

0

精彩评论

暂无评论...
验证码 换一张
取 消