比较Java中的两个值

皮库

我有两个值,我试图比较它们,但得到了磨损的结果:

    public void subtotal() throws Exception {
    WebDriverWait wait = new WebDriverWait(session.driver, 100);
    double subtotal_price = 0;
    DecimalFormat decimal = new DecimalFormat("0.00");
    WebElement subtotal = wait.until(ExpectedConditions.visibilityOf( element("Subtotal_cart")));
    Float subtotal_value = Float.parseFloat(subtotal.getText().substring(1));
    logger.info("subtotal_value"+subtotal_value);
    File file = new File("ItemUPC/ItemUPC.txt");
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String[] line = sc.nextLine().split("[|]");
        String price = line[2];
        subtotal_price = subtotal_price + Double.parseDouble(price);
    }
    logger.info("subtotal_price"+subtotal_price);
    if ((subtotal_value)==(subtotal_price))
    {
        logger.info("Subtotals updated");
    }
    else
    {
        logger.info("Subtotals not updated");
    }
}

以下是ItemUPC文件:

2|BATH BENCH|19.00
203|ORANGE BELL|1.78

当我打印 subtotal_price 和 Subtotal_value 的值时,我得到的都是 20.78,但是当它在 if 语句中进行比较时,我得到的输出为“Subtotals not updated” 不确定我哪里出错了。有人可以帮忙吗?谢谢你。

菲利普·拉格

由于浮点类型及其十进制数的二进制表示之间的精度差异,比较浮点数可能具有挑战性。

您有两个简单的选择:

  1. 将两个值之间的差值的绝对值与epsilon或阈值进行比较
  2. 使用BigDecimal为您的替代品Floatdouble变量类型

示例 1:

// simplification that may fail in certain edge cases
static final double EPSILON = .001; // acceptable error - adjust to suit your needs
if (Math.abs(subtotal_price - subtotal_value) < EPSILON) {
  logger.info("Subtotals updated");
}
// ...

示例 2:

BigDecimal subtotal_price = new BigDecimal("0");
// ...
BigDecimal subtotal_value = new BigDecimal(subtotal.getText().substring(1));
// ...
if(subtotal_price.compareTo(subtotal_value) == 0) {
  logger.info("Subtotals updated");
}
// ...
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章