【问题标题】:How i can covert a string '$1400.00' to an int 1400.00 in Java我如何在 Java 中将字符串 '$1400.00' 转换为 int 1400.00
【发布时间】:2019-09-05 00:25:20
【问题描述】:

谁能帮我在 Java 中将包含数字和字符的字符串转换为整数?

例如,我想将 String amount = $100.00 转换为 int。

我尝试使用integer.parseInt();,但它给出了错误。

String Checkamount = $1400.00; //Convert web element to string.
int intAmount = Integer.parseInt(Checkamount);

预期结果:1400.00

错误信息

线程“main”java.lang.NumberFormatException 中的异常:对于输入字符串:“$1,400.00” 在 java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)

【问题讨论】:

  • 您对1400.00 的预期结果不是int
  • 您可以首先在字符串上调用replaceAll,以删除美元符号。请记住从正则表达式解析器中转义美元符号(使用"\\$")。另外,我怀疑您是否真的想使用 int - 看起来您正在处理可能包含非整数的值。
  • NumberFormat.getCurrencyInstance(Locale.US).parse("$1,400.00").doubleValue()

标签: java


【解决方案1】:

首先,1400.00 不能转换为 int,因为它有小数位。您需要使用变量类型doublefloat 来存储这个值。

在转换为数字之前,使用 Java 的 replace() 替换掉不需要的字符。例如。

amount = amount.replace('$', '').replace(',', '');
double doubleAmount = Double.parseDouble(amount);

有一种更简洁的方法可以使用适当的正则表达式进行替换,但这应该可以。

【讨论】:

  • 您好,感谢您的回复。我已经尝试过了,但它显示如下错误:线程“main”中的异常 java.lang.NumberFormatException: For input string: "1 415.00" at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java: 2054) 在 java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122) 在 java.base/java.lang.Float.parseFloat(Float.java:461) 在 anzTesting.testing.login(testing .java:34)
  • @Antony 1 415.00 中有一个空格而不是 , - 为了获得更好的响应,您需要明确预期的输入(和输出;))
  • 我的示例代码在这里我使用 selenium web 驱动程序从我的银行帐户获取输入。 Sample code.
  • 确保用空字符而不是空格替换字符。我想你可能会使用' ' 而不是''
【解决方案2】:
  • 金额不得以整数形式存储。
  • 金额存储在 BigDecimal 中以保持准确性。 (ref)

要使用货币字符串,您可以将NumberFormatlocale 结合使用。

public static void main(String[] args) {
    Locale locale = new Locale("en", "US");

    NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);

    try {
        String input = "$123,456,56.2";
        Number money = currencyFormat.parse(input);
        BigDecimal moneyAmount = BigDecimal.valueOf(money.doubleValue());
        //Do whatever you want with money amount here.
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
}

【讨论】:

    【解决方案3】:
    import java.util.regex.Pattern;
    import java.util.Locale;
    import java.math.BigDecimal;
    import java.text.ParseException;
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    public class DollarToInt{
        public static void main(String[] args) throws ParseException{
            //Method 1 --> ERROR WHEN \n incl
            String amount="$1,32423410.00"; 
            amount=amount.replace("$", "").replace(",", "");
            double toDouble= Double.parseDouble(amount);
    
            //Method 2 --> IGNORES \n
            String amount2 = "$1,2131000.00";
            DollarToInt method2= new DollarToInt();
            BigDecimal toBigDecimal=method2.parse(amount2, Locale.US);
    
            //Method 3 -> WHEN \n incl REMOVES VALUES RIGHT OF \n
            Double toDouble3= NumberFormat.getCurrencyInstance(Locale.US).parse("$1, 400.00").doubleValue();
    
            System.out.println(toDouble); //M1
            System.out.println(toBigDecimal); //M2
            System.out.println(toDouble3); //M3
        }
    
         public BigDecimal parse(final String amount, final Locale locale) throws ParseException {
            final NumberFormat format = NumberFormat.getNumberInstance(locale);
            if (format instanceof DecimalFormat) {
                ((DecimalFormat) format).setParseBigDecimal(true);
            }
            return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]",""));
        }
    }
    

    我尝试了两种解析美元格式的方法,我认为方法 2 效果更好,而且是更好的方法。 参考:Converting different countrys currency to double using java

    【讨论】:

      【解决方案4】:

      使用子字符串。

      String value = amount.substring(1,amount.length());
      

      “值”现在将只存储不带美元符号的数字。

       double doubleAmount = Double.parseDouble(value);
      

      我认为这会有所帮助。

      【讨论】:

        【解决方案5】:

        这里的东西 1400.00 不能转换为 int。 但是如果你想要没有小数点,那么这里是完整的解决方案

            String amount = "$1400.00";
            amount = amount.replace('$', ' ');
            int intAmount= (int)Double.parseDouble(amount);
        

        【讨论】:

        【解决方案6】:

        一种可能的解决方案是使用NumberFormat - 唯一的限制是确保您使用的是适当的Locale

        例如...

        NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
        try {
            Number number = formatter.parse("$1000.40");
            System.out.println(number);
            System.out.println(number.intValue());
            System.out.println(number.doubleValue());
        } catch (ParseException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        

        将打印

        1000.4
        1000
        1000.4
        

        您也可以输入$1,000.40,它会给您相同的结果。

        同样,这里需要注意的是,NumberFormatter 将期望输入与输出相同。比如上面的NumberFormatter会输出一个double值1000.6$1,000.60

        【讨论】:

          猜你喜欢
          • 2015-01-29
          • 2021-08-01
          • 1970-01-01
          • 2013-11-03
          • 2012-10-02
          • 2018-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多