如何在不损失精度的情况下解码 NSDecimalNumber?

Ant*_*hko 1 nsdecimalnumber swift codable jsondecoder

有没有办法告诉 JSONDecoder 将传入的小数转换为字符串?

 public struct Transaction: Decodable
 {
    public let total: NSDecimalNumber?


    enum CodingKeys: String, CodingKey {
        case total = "AMOUNT"

    }

    public init(from decoder: Decoder) throws
    {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let total = try values.decode(Decimal.self, forKey: .total)
        self.total = NSDecimalNumber(decimal: total);
    }

 }
Run Code Online (Sandbox Code Playgroud)

考虑当 AMOUNT 类似于 397289527598234759823475455622342424358363514.42 时会发生什么

我想使用我拥有的代码,我会得到 nonConformingFloatDecodingStrategy 异常而无法从中恢复或失去精度。

围绕愚蠢的 swift Decimal 的斗争被记录在了所有的地方,特别是在这里:

使 NSDecimalNumber 可编码

Dáv*_*tor 5

问题是这JSONDecoder只是一个包装器JSONSerialization,它在Double内部将十进制数字解码为Decimal. 遗憾的是,除非您创建自己的 JSON 解码器,否则在使用来自 JSON 的数字小数时无法解决此问题。

目前唯一可能的解决方法是更改​​您的后端以将所有十进制数作为Strings发送,然后在将它们Decimal解码为s 后将它们转换为Strings。

有关更多信息,请查看这个未解决的 Swift 错误:SR-7054