When working with decimals encoding a value of e.g 68.32
does not result in the same value when decoding it afterwards.
I'm using the suggestion from https://forums.swift.org/t/decimal-has-no-rounded/14200/12 to round the value before encoding it.
Might this be a bug in the JSONEncoder
/ JSONDecoder
? Is there any reliable workaround?
Here is an example code:
import Foundation
let decimalValue: Decimal = 68.32 // 68.31999999999998976
let roundedDecimalValue = decimalValue.rounded(2, .plain) // 68.32
do {
let data = try JSONEncoder().encode(roundedDecimalValue)
let decodedDecimal = try JSONDecoder().decode(Decimal.self, from: data) // 68.31999999999999
print(decodedDecimal)
} catch {}
extension Decimal {
mutating func round(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) {
var localCopy = self
NSDecimalRound(&self, &localCopy, scale, roundingMode)
}
func rounded(_ scale: Int, _ roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
var result = Decimal()
var localCopy = self // 68.31999999999998976
NSDecimalRound(&result, &localCopy, scale, roundingMode)
return result // 68.32
}
}
Edit: I've ended up implementing a solution based on Swift: Decode imprecise decimal correctly