You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Selenium中java.lang.NumberFormatException错误排查求助

问题解决:Java Selenium数字格式异常处理

错误原因拆解

你的代码里有三个核心问题导致NumberFormatException:

  1. 字符串直接做乘法是错误操作:unitPrice是String类型,unitPrice * 2在Java里会把字符串重复2次(比如"99"*2变成"9999"),不是数值相乘,之后转int自然会出错。
  2. 价格字符串包含非数字字符:页面上的价格文本一般带货币符号(比如¥、$)、逗号或者单位(元),直接用Integer.parseInt解析这类字符串,必然抛出格式异常。
  3. 断言逻辑顺序错误:Assert.assertEquals的第一个参数是预期值,第二个是实际值,你搞反了;而且totalPrice也是字符串,需要转成数值再比较。

修正步骤

  1. 清洗价格字符串:先提取字符串里的纯数字部分(包括小数),用正则表达式去掉所有非数字和小数点的字符。
  2. 转成数值类型计算:把清洗后的字符串转成double(价格常含小数,用int会丢失精度),再做乘法计算预期总价。
  3. 修正断言逻辑:把页面拿到的总价也转成数值,和计算后的预期值比较,同时允许微小精度误差(避免浮点数计算的精度问题)。

修正后的代码

// 工具方法:提取价格文本中的纯数字(支持小数)
private static double parsePrice(String priceText) {
    // 去掉所有非数字和小数点的字符
    String cleanPrice = priceText.replaceAll("[^0-9.]", "");
    return Double.parseDouble(cleanPrice);
}

// 验证购物车价格逻辑
String unitPriceText = driver.findElement(By.xpath("//span[@class='m-basket-card__price m-basket-card__price--main']")).getText();
System.out.println("single price of the product= " + unitPriceText);
String totalPriceText = driver.findElement(By.xpath("//sub[@class='js-card-price']")).getText();
System.out.println("total price of the cart = " + totalPriceText);

// 转成数值计算预期总价
double unitPrice = parsePrice(unitPriceText);
double expectedTotal = unitPrice * 2;
double actualTotal = parsePrice(totalPriceText);

// 断言,允许0.01的精度误差
Assert.assertEquals(expectedTotal, actualTotal, 0.01);

额外提示

  • 如果页面价格是整数,也可以用Integer.parseInt,但建议用double兼容更多场景。
  • 若价格用逗号做千位分隔符(比如1,000),可以先替换逗号再清洗:priceText.replace(",", "").replaceAll("[^0-9.]", "")。

内容的提问来源于stack exchange,提问作者Muhammet AYDIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:20:28