【问题标题】:How would I decode a NSDecimalNumber without loss of precision?如何在不损失精度的情况下解码 NSDecimalNumber?
【发布时间】:2019-06-28 11:12:34
【问题描述】:

有没有办法告诉 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);
    }

 }

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

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

在整个 s.o. 中都记录了围绕愚蠢的 swift Decimal 的斗争。 特别是这里:

Making NSDecimalNumber Codable

【问题讨论】:

  • 你必须把它作为String 在你的JSON 开头,否则它会先把它转换成Double,然后再转换成你的类型。
  • 是的@LeoDabus,这仅适用于您自己编码和解码值的情况,并且对于您无法控制的远程系统的数据完全有用
  • @AntonTropashko 试试这个stackoverflow.com/a/55131900/2303865

标签: swift codable nsdecimalnumber jsondecoder


【解决方案1】:

问题在于JSONDecoder 只是JSONSerialization 的包装器,它将十进制数在内部解码为Double,并且仅在将它们转换为Decimal 之后。遗憾的是,除非您创建自己的 JSON 解码器,否则在使用 JSON 中的数字小数时无法解决此问题。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多