draveness / blog-comments

面向信仰编程
https://draveness.me
140 stars 6 forks source link

为什么 0.1 + 0.2 = 0.3 - 面向信仰编程 · /whys-the-design-decimal-and-rational #201

Closed draveness closed 2 years ago

draveness commented 4 years ago

https://draveness.me/whys-the-design-decimal-and-rational/

pymongo commented 4 years ago

如何避免Decimal类型序列化为JSON格式时的精度丢失问题?因为JSON就没有Decimal数据类型。 以我经验Ruby on Rails和Rust会将Decimal转成字符串去避免转JSON出现的精度丢失。

我最喜欢用的Decimal结构体是长这样 pub struct Decimal { // Bits 16-23: a value between 0-28 that indicates the scale // Bit 31: the sign of the Decimal value flags: u32, hi: u32, lo: u32, mid: u32, } Decimal比较恶心的是「不太容易」序列化/反序列化为bincode格式(Rust一种比JSON性能更好的序列化格式),也是要转成字符串才能序列化成bincode