MongoDB - 十进制类型的值怎么样? [英] MongoDB - What about Decimal type of value?

查看:28
本文介绍了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. 您需要使用整数类型并将值保持在美分是什么意思?这是否意味着如果我要存储 1.34 美元,那么我应该存储 134 美分?
  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 文档中 建模货币数据 和是 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天全站免登陆