Swift:正确解码不精确的小数

时间:2019-03-12 22:10:26

标签: swift decodable nsdecimalnumber

我需要从this question正确解码(plt.scatter协议)不精确的十进制值,我知道如何正确处理Decimal实例化,但是在解码时如何执行呢?

如果尝试将任何数字初始化为字符串

Decodable

我得到if let value = try! container.decode(String.self, forKey: .d) { self.taxAmount = Decimal(string: value) }

如果尝试将130.43初始化为小数

Fatal Error: "Expected to decode String but found a number instead."

解码时有没有办法使用这两个构造函数中的任何一个?

  • if let value = try! container.decode(Decimal.self, forKey: .d) { //value.description is 130.43000000000002048 self.d = Decimal(string: value.description) //making subtotal to be also 130.43000000000002048 and not 130.43 }
  • NSDecimalNumber(string: "1.66")
  • NSDecimalNumber(value: 166).dividing(by: 100)
  • Decimal(166)/Decimal(100)

这是我从外部服务收到的JSON的简化版本:

Decimal(sign: .plus, exponent: -2, significand: 166)

注意:我无法更改接收到的要解码的内容,我只能使用十进制数字。

0 个答案:

没有答案