From c6157e62e900e2ecb63800048c1106f231b49760 Mon Sep 17 00:00:00 2001 From: Andrew Heard Date: Wed, 28 Feb 2024 12:41:08 -0500 Subject: [PATCH] Add comment about converting to `Decimal` before encode --- Sources/GoogleAI/JSONValue.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sources/GoogleAI/JSONValue.swift b/Sources/GoogleAI/JSONValue.swift index a279e91..5ce52cd 100644 --- a/Sources/GoogleAI/JSONValue.swift +++ b/Sources/GoogleAI/JSONValue.swift @@ -75,6 +75,11 @@ extension JSONValue: Encodable { case .null: try container.encodeNil() case let .number(numberValue): + // Convert to `Decimal` before encoding for consistent floating-point serialization across + // platforms. E.g., `Double` serializes 3.14159 as 3.1415899999999999 in some cases and + // 3.14159 in others. See + // https://forums.swift.org/t/jsonencoder-encodable-floating-point-rounding-error/41390/4 for + // more details. try container.encode(Decimal(numberValue)) case let .string(stringValue): try container.encode(stringValue)