【问题标题】:Comparing two values in Java比较Java中的两个值
【发布时间】:2020-08-31 19:16:22
【问题描述】:

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

    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 语句中进行比较时,我得到的输出是“未更新小计” 不知道我哪里错了。有人可以帮忙吗?谢谢。

【问题讨论】:

  • @Aaron 我认为这不对。 OP 将原始double 与对象Float 进行比较,该对象将被拆箱以进行比较。问题在于精度,而不是值是否被装箱。
  • @DawoodibnKareem 谈论精度,结果显示两者均为 20.78。
  • @Piku doublefloat 通常都不完全存储十进制数字,因此两个值都不完全是 20.78。这导致您出现问题的原因是您试图将doublefloat 进行比较。对于十进制算术,我强烈建议使用 BigDecimal 类,它不存在精度问题。
  • @DawoodibnKareem 你能给我一个例子吗?谢谢
  • 网上有大量使用BigDecimal类的例子。

标签: java selenium


【解决方案1】:

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

您有两个简单的选择:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多