首页
/ Apollo iOS项目中Decimal数值精度问题的分析与解决

Apollo iOS项目中Decimal数值精度问题的分析与解决

2025-06-17 07:10:53作者:尤峻淳Whitney

在iOS开发中使用Apollo GraphQL客户端时,处理Decimal数值类型可能会遇到意外的精度问题。本文将深入分析这个常见问题的成因,并提供专业的解决方案。

问题现象

开发者在使用自定义标量类型Decimal时,发现当发送6.99这样的数值时,后端实际接收到的却是6.990000000000002。这种精度偏差会导致业务逻辑出现错误,特别是在金融计算等对精度要求严格的场景中。

根本原因分析

  1. 浮点数精度问题:计算机使用二进制表示浮点数时,某些十进制小数无法精确表示,导致舍入误差。

  2. 自定义标量实现缺陷:当前实现中虽然使用了NumberFormatter进行截断处理,但在JSON序列化/反序列化过程中可能绕过了这个处理逻辑。

  3. 类型转换问题:在Double和Decimal之间的转换过程中没有完全控制精度。

解决方案

方案一:优化自定义Decimal标量实现

public struct Decimal: CustomScalarType, Hashable {
    private static let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.maximumFractionDigits = 2
        formatter.roundingMode = .halfUp
        formatter.numberStyle = .decimal
        return formatter
    }()
    
    public let value: Foundation.Decimal
    
    public init(_ value: Foundation.Decimal) {
        self.value = value
    }
    
    public init(_jsonValue value: JSONValue) throws {
        if let stringValue = value as? String,
           let decimalValue = Foundation.Decimal(string: stringValue) {
            self.value = decimalValue
        } else if let doubleValue = value as? Double {
            self.value = Foundation.Decimal(doubleValue).rounded(2)
        } else {
            throw JSONDecodingError.couldNotConvert(value: value, to: Decimal.self)
        }
    }
    
    public var _jsonValue: JSONValue {
        return Decimal.formatter.string(from: value as NSNumber) ?? value.description
    }
}

extension Foundation.Decimal {
    func rounded(_ scale: Int) -> Foundation.Decimal {
        var result = Foundation.Decimal()
        var localCopy = self
        NSDecimalRound(&result, &localCopy, scale, .bankers)
        return result
    }
}

方案二:直接使用Double类型

对于大多数场景,使用Double类型并配合适当的舍入策略可能更简单高效:

let value = 6.99
let roundedValue = (value * 100).rounded() / 100

最佳实践建议

  1. 明确精度需求:在金融等关键领域,应该使用专门的十进制算术库而非原生浮点类型。

  2. 前后端一致:确保前后端使用相同的精度处理逻辑,避免跨系统精度差异。

  3. 单元测试:为涉及货币计算的代码添加严格的单元测试,验证边界条件。

  4. 版本升级:保持Apollo iOS客户端为最新版本,以获得最佳稳定性和功能支持。

总结

处理数值精度是移动开发中的常见挑战。通过理解计算机数值表示的基本原理,选择适当的处理策略,并实施严格的验证机制,可以有效避免这类问题的发生。在Apollo iOS项目中,开发者应当根据具体业务需求,选择最适合的数值处理方案。

登录后查看全文
热门项目推荐
相关项目推荐