mongo的浮点型精度问题
-
在mongo计算分组求和,如10+25.66 = 35.6599999999 是这个结果。
这是浮点数机制决定的。所有系统的浮点数只要是按IEEE浮点数标准来的,都是这个样子。少数语言在显示的时候做了处理,比如PHP。其他平台就需要自己处理下。
不只是mongo,大部分的数据库都存在这个问题,各种合计都会有误差,为此有一个数据类型叫Decimal,使用文本存放数字,数据库合计之类的就没有误差了。当然程序中也要有这个数据类型,然后操作各种蛋痛各种不直观。
替代的方案是直接用int,以分为单位而不是以元为单位。当然前台显示时要各种处理,反正就没一个简洁的方案。
.
-
请使用MongoDB3.4,支持Decimal类型
-
可使用 NumberDecimal
The
decimal
BSON typemongo
shelldecimal
values are assigned and queried using theNumberDecimal()
constructor. The following example adds a document containing gas prices to agasprices
collection:db.gasprices.insert{ "_id" : 1, "date" : ISODate(), "price" : NumberDecimal("2.099"), "station" : "Quikstop", "grade" : "regular" }
The following query matches the document above:
db.gasprices.find( { price: NumberDecimal("2.099") } )
For more information on the
decimal
type, see NumberDecimal.Converting Values to Decimal
A collection's values can be transformed to the
decimal
type by performing a one-time transformation or by modifying application logic to perform the transformation as it accesses records.One-Time Collection Transformation
A collection can be transformed by iterating over all documents in the collection, converting the monetary value to the
decimal
type, and writing the document back to the collection.NOTE
It is strongly advised to add the
decimal
value to the document as a new field and remove the old field later once the new field's values have been verified.本帖下載内容已隐藏,请登入以查看隐藏内容