SwiftUI文档应用:如何限制JSONEncoder的Double输出精度?
解决Swift JSONEncoder保留指定小数精度的问题
当使用Swift的JSONEncoder编码大型Double数组时,默认的精度输出会导致JSON文件体积远大于原CSV,核心原因是Double被编码为带过多冗余小数位的字符串。要限制为4位小数,有两种可靠的实现方式:
1. 在自定义数据结构中针对性处理编码
这种方式不会全局修改Double的编码行为,仅作用于你的文档数据结构,更安全可控:
假设你的数据结构如下:
struct DocumentData: Encodable { var numericValues: [Double] }
修改它的encode(to:)方法,对每个Double做四舍五入处理后再编码:
struct DocumentData: Encodable { var numericValues: [Double] enum CodingKeys: String, CodingKey { case numericValues } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) // 四舍五入到4位小数 let roundedValues = numericValues.map { ($0 * 10000).rounded() / 10000 } try container.encode(roundedValues, forKey: .numericValues) } }
2. 全局扩展Double的编码逻辑(谨慎使用)
如果你的所有Double都需要统一精度,可以全局扩展Double实现自定义编码,但注意这会影响整个项目中Double的JSON编码行为:
extension Double: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let roundedValue = (self * 10000).rounded() / 10000 try container.encode(roundedValue) } }
补充说明
- 四舍五入逻辑:
($0 * 10000).rounded() / 10000是将数值放大10000倍后取整,再缩小回原比例,实现4位小数的四舍五入。 - 若允许将Double编码为字符串类型,也可以用
String(format: "%.4f", self)生成固定格式的字符串后再编码,但后续解析时需要将字符串转回Double。
内容的提问来源于stack exchange,提问作者Tahmid Azam
相关产品推荐
相关产品推荐

