MongoDB-十进制值类型呢? [英] MongoDB - What about Decimal type of value?

查看:132
本文介绍了MongoDB-十进制值类型呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为一个与财务相关的小型项目学习和应用MongoDB.

I am currently learning and applying MongoDB for a small financial related project.

当我阅读运行中的MongoDB 时,它说:

BSON数值类型通常引起的唯一其他问题是 缺乏十进制支持.也就是说,如果您打算 在MongoDB中存储货币值,您需要使用整数类型 并保持数值为美分.

The only other issue that commonly arises with BSON numeric types is the lack of decimal support. This means that if you’re planning on storing currency values in MongoDB, you need to use an integer type and keep the values in cents.


我与金融相关的产品将涉及某些货币价值,但我对上述说法感到有些困惑或担心.这是我的问题:


My financial related product will involve some currency values, but I am little bit confused or worried about the above statement. Here are my questions:

  1. 我可以在项目中的currency values中使用double吗?
  2. 如果直接对它们使用double会发生什么或后果?
  3. 如果十进制类型对于金融产品来说是必不可少的,那么使用MongoDB是一个坏主意吗?
  4. you need to use an integer type and keep the values in cents是什么意思?这是否意味着如果我要存储1.34 dollars,那么我应该存储134 cents?
  1. Can I use double for those currency values in my project?
  2. What will happen or is the consequences if I directly use double for them?
  3. If decimal type is an must-have thing for financial product, is that a bad idea to use MongoDB?
  4. What does it mean you need to use an integer type and keep the values in cents? Does it mean that if I am going to store 1.34 dollars, then I should store 134 cents?

谢谢

推荐答案

如果您想要出于财务目的的精确表示,则双精度或浮点值不适用,因为小数部分会产生舍入误差.某些十进制值不能使用基于二进制的浮点表示,而必须近似.

If you want an exact representation for financial purposes, then doubles or floating point values are unsuitable as the fractional parts are subject to rounding error. Certain decimal values cannot not be represented using binary-based floating points and must be approximated.

有关技术性较差的介绍,请参见四舍五入浮点数的麻烦;如果您想看看,请阅读每位计算机科学家应该知道的内容关于浮点算法.

For a less technical intro, see The trouble with rounding floating point numbers; if you want to geek out, then read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

建议使用整数类型(以美分存储值)是为了避免潜在的舍入误差.这种方法被描述为"使用比例因子",用于建模货币数据,并且是MongoDB 3.2和更早版本的常规解决方法.

The recommendation of using an integer type (storing the value in cents) is to avoid potential rounding errors. This approach is described as "Using a Scale Factor" in the MongoDB documentation for modelling monetary data and is a general workaround for MongoDB 3.2 and earlier.

MongoDB 3.4包括一个新的十进制BSON类型为处理货币数据字段提供了精确的精度.

MongoDB 3.4 includes a new Decimal BSON type which provides exact precision for manipulating monetary data fields.

这篇关于MongoDB-十进制值类型呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆