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

数据过滤逻辑异常:<=运算符数值对比校验失效问题排查

价格过滤条件校验失效排查

从服务器获取数据后,通过if条件语句执行数据过滤时,出现使用<=运算符对比服务器解析的价格数据与本地price列表数据时校验未按预期生效的问题,相关代码如下:

List speed = [
  7.4,
  11,
  22,
];

List<double> price = [
  0.20,
  0.25,
  0.30,
  0.35,
  0.40,
  0.45,
  0.50,
];

if ((w.power.toInt() == speed[filters.minSpeed]) &&
            (double.parse(w.formattedPrice.substring(1)) <=
                price[filters.maxPrice]) ||
        (i.public == filters.ownershipStationPublic ||
            filters.ownershipStationAll)) {
  log(double.parse(w.formattedPrice.substring(1)).toString());
  log('My price: ${price[filters.maxPrice].toString()}');
  filteredStations.add(i);
}

排查方向

  • 运算符优先级混乱:原if语句中&&与||未明确分组,逻辑判断顺序可能偏离预期。当前代码逻辑可能被解析为(A && B) || C || D,但实际需求大概率是(A && B) || (C || D),建议给||两侧的条件都加上外层括号,明确逻辑边界:

    if (
      ((w.power.toInt() == speed[filters.minSpeed]) && 
       (double.parse(w.formattedPrice.substring(1)) <= price[filters.maxPrice])) || 
      (i.public == filters.ownershipStationPublic || filters.ownershipStationAll)
    ) {
      // 原有逻辑代码
    }
    
  • 浮点数精度误差:double.parse解析字符串可能产生二进制精度问题,比如服务器价格解析后是0.2,本地列表的0.20看似相等,但二进制存储可能存在细微差异,导致<=判断失效。可以将两边统一保留两位小数后再对比:

    double parsedPrice = double.parse(w.formattedPrice.substring(1));
    parsedPrice = double.parse(parsedPrice.toStringAsFixed(2));
    double targetPrice = double.parse(price[filters.maxPrice].toStringAsFixed(2));
    
    // 用处理后的价格进行判断
    if (parsedPrice <= targetPrice) {
      // ...
    }
    
  • 索引取值越界:检查filters.maxPrice是否为price列表的合法索引(范围0~6,因为price有7个元素)。如果索引超出范围,会取到错误的价格值,直接导致对比逻辑失效。可以添加日志确认索引值:

    log('maxPrice索引值: ${filters.maxPrice}');
    log('目标价格: ${price[filters.maxPrice]}');
    
  • 前置条件干扰:如果w.power.toInt() == speed[filters.minSpeed]这个前置条件不成立,整个&&分支会直接失效,逻辑会走后面的||分支,看起来像是价格校验没生效。可以单独打印这个前置条件的判断结果,确认是否符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:55:23