Pregunta

I am creating a budget program in java and need to check to see if the user inputs a valid dollar amount, specifically 2 decimal places. There is no specification on how this should be done.

This is my current attempt but the logic is wrong

  aExpense5.addActionListener(new ActionListener()
  {
     public void actionPerformed(ActionEvent e)
     {
        String desc = aExpense3.getText();
        String value = aExpense4.getText();
        double fValue = 0;

        try
        {
           fValue = Double.valueOf(value);
        }
        catch (NumberFormatException d)
        {
           JOptionPane.showMessageDialog(null, "Invalid Number1");
        } 
           double dValue = (fValue * 10) % 10;

           if (dValue <= 0)
           {
              updateExpenseList(desc, fValue);
           }
           else
           {
              JOptionPane.showMessageDialog(null,"invalid Number");
           }
     }
  });
¿Fue útil?

Solución 2

Try something like:

if (fValue*100 == (int)(fValue*100)) { 
    //fValue had 2 decimal places or less 
}

If fValue = 0.11 then fValue*100 = 11. So you'd have 11 == (int)11 which is true.

If fValue = 0.111 then fValue*100 = 11.1. So you'd have 11.1 == (int)11.1 which is false.

Otros consejos

You can use regex:

if (value.matches("\\d*\\.\\d\\d")) {
    // the number string has two decimal places
}

This regex allows for optional whole number part, ".05" would match.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top