【问题标题】:Checking for proper decimal format Java检查正确的十进制格式 Java
【发布时间】:2023-03-14 15:39:02
【问题描述】:

我正在用 Java 创建一个预算程序,需要检查用户是否输入了有效的美元金额,特别是小数点后 2 位。没有关于应该如何完成的规范。

这是我目前的尝试,但逻辑错误

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

【问题讨论】:

    标签: java decimalformat


    【解决方案1】:

    你可以使用正则表达式:

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

    此正则表达式允许可选的整数部分,“.05”将匹配。

    【讨论】:

      【解决方案2】:

      尝试类似:

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

      如果fValue = 0.11 那么fValue*100 = 11。所以你会有11 == (int)11,也就是true

      如果fValue = 0.111,那么fValue*100 = 11.1。所以你会有11.1 == (int)11.1,即false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2012-09-30
        • 2017-11-11
        相关资源
        最近更新 更多