美文网首页我爱编程
mongodb double 精度解决方案

mongodb double 精度解决方案

作者: Josen_Qu | 来源:发表于2017-07-29 22:25 被阅读3557次

mongodb double精度问题所学到的知识

背景介绍:

由于目前本人在做一个涉及计费的一个项目,中间有统计计费,比如一个公司合同下 每个账号的每天/每月的消费情况。
比如查今天的流水账,统计费用最先想到的是mongodb的聚合函数match group sum ,由于金额大部分有小数点,就搞了double 类型,那么问题来了,java的double计算都是有精度问题的,比如99.3 - 0.2的结果99.0999999999.

方案改进:

mongodb 对double 聚合sum 的结果也是如此,毕竟硬件对double 精度就这样了。

List<Document> pipeline = Arrays.asList(new Document("$match", map),
              new Document("$group", new Document("_id", "$" + BaseInfoSo.CONT_ID).append("totalExpense",
                      new Document("$sum", "$" + BaseInfoSo.EXPENSE))));
      AggregateIterable<Document> iterable = collection.aggregate(pipeline);

然后就只能把每次消费拿出来自己统计,这时候用到的是addToSet / push,刚开始用了addToSet 感觉不对,然后发现addToSet是去重复的,push可重复的。
就用了push。拿出来后再用bigDecimal计算。

List<Document> pipeline = Arrays.asList(new Document("$match", map),
                new Document("$group", new Document("_id", "$" + BaseInfoSo.CONT_ID).append("eachExpense",
                        new Document("$push", "$" + BaseInfoSo.EXPENSE))));
        AggregateIterable<Document> iterable = collection.aggregate(pipeline);

由于用到了mongodb的增量更新费用,但是mongodb对double的更新同样是存在精度问题

Bson filter = Filters.eq(BaseInfoSo.CONT_ID,dto.getContId());
            Document doc = new Document("$inc", new Document(BaseInfoSo.CALL_TIMES, 1)
                    .append(BaseInfoSo.BALANCE, -dto.getExpense()))
                    .append("$set", new Document(BaseInfoSo.MODIFY_TIME,now));
collection.findOneAndUpdate(filter, doc, new FindOneAndUpdateOptions().upsert(false));

但是又不想把金额作为查询条件,期间很可能有变动的。
经查询发现mongodb从3.4版本开始支持 decimal128 类型,
具体参考https://en.wikipedia.org/wiki/Decimal128_floating-point_format
mongodb字段类型可存为Decimal28类型,上面的更新可改为


            Bson filter = Filters.eq(BaseInfoSo.CONT_ID,dto.getContId());
            Document doc = new Document("$inc", new Document(BaseInfoSo.CALL_TIMES, 1)
                    .append(BaseInfoSo.BALANCE, new Decimal128(BigDecimal.valueOf(-dto.getExpense()));
            collection.findOneAndUpdate(filter, doc, new FindOneAndUpdateOptions().upsert(false));
        

但是java double 和 mongodb decimal128之间并不能直接转换,这就需要我们自己做转换了
在java > mongodb:

向mongodb中插入java bean dto:

            Document doc2 = Document.parse(GsonUtil.getInstance().toJson(dto));
            System.out.println("转换前:"+doc2);
            Document appendDoc = new Document();
             Iterator<Entry<String, Object>> it = doc2.entrySet().iterator();
             while(it.hasNext()){
                 Entry<String, Object> e = it.next();
                    String key = e.getKey();
                    Object value = e.getValue();
                    if(value instanceof Double){
                        it.remove();
                        System.out.println(key+" is double type");
                        appendDoc.append(key,  new Decimal128(BigDecimal.valueOf((Double)value)));
                    }
             }
            doc2.putAll(appendDoc);
            System.out.println("转换后:"+doc2);
            collection.insertOne(doc2);

mongodb>java

        Document doc = cur.next();
        Document appendDoc = new Document();
         Iterator<Entry<String, Object>> it = doc.entrySet().iterator();
         while(it.hasNext()){
             Entry<String, Object> e = it.next();
                String key = e.getKey();
                Object value = e.getValue();
                if(value instanceof Decimal128){
                    it.remove();
                    System.out.println(key+" in mongodb is Decimal128 type");
                    appendDoc.append(key,  ((Decimal128) value).bigDecimalValue().doubleValue());
                }
         }
         doc.putAll(appendDoc);

再直接用json工具直接反序列化成java 对象就可以了。

 JAVADto dto = GsonUtil.getInstance().fromJson(doc.toJson(), JAVADto.class);

后续

后面发现不用这么麻烦的解析,我们可以自己修改document 的解析器

image.png

String json = MongoDoc2JsonUtils.toJson(doc);
这样就只有数字了

相关文章

  • mongodb double 精度解决方案

    mongodb double精度问题所学到的知识 背景介绍: 由于目前本人在做一个涉及计费的一个项目,中间有统计计...

  • 2018-11-04-1

    java double计算精度问题 double计算防止精度丢失:方案:将double转成bigDecimalSy...

  • double丢失精度解决方案

    背景 double类型做计算时,容易出现精度丢失。举例如下:如下代码进行除法计算: 预期:969.9215,而实际...

  • C语言学习 - 浮点型数据类型

    在 C语言中,浮点型数据类型可分为:float(单精度)、double(双精度)、long double(长双精度...

  • 数据类型

    double数字精度

  • 浮点类型解析

    一、类型定义浮点类型有float、double、long double类型,即单精度、双精度、长双精度,一般情况下...

  • 记一道精度转换面试题

    解释:1.向上转换不会丢失精度(float--->double),向下转才会丢失精度(double--->floa...

  • 代码中的小细节(三)让代码远离 bug

    禁止使用构造方法 BigDecimal(double) BigDecimal(double) 存在精度损失风险,在...

  • double,float精度

    对于这个问题,还是得看计算机原理。 我们这个问题,可以用科学计数法来表示,1.222222332412341234...

  • double精度问题

    浮点数存储的是近似值而不是确切的值;所以double的值存在不确定情况在mysql中:使用DECIMAL,在jav...

网友评论

    本文标题:mongodb double 精度解决方案

    本文链接:https://www.haomeiwen.com/subject/hpohottx.html