简体   繁体   English

Java快钱代表?

[英]Java fast money representation?

I'm working on a real time application that deals with money in different currencies and exchange rates using BigDecimal, however I'm facing some serious performance issues and I want to change the underlying representation.我正在开发一个实时应用程序,该应用程序使用 BigDecimal 处理不同货币和汇率的货币,但是我面临一些严重的性能问题,我想更改底层表示。

I've read again and again that a good and fast way of representing money in Java is by storing cents (or whatever the required precision is) using a long.我一遍又一遍地读到,在 Java 中表示货币的一种又好又快的方法是使用 long 存储美分(或任何所需的精度)。 As one of the comments pointed out, there are some libs with wrappers that do just that, such as FastMoney from JavaMoney .正如其中一条评论指出的那样,有一些带有包装器的库可以做到这一点,例如来自JavaMoney 的 FastMoney

Two questions here.这里有两个问题。

  1. Is it always safe to store money as a long (or inside a wrapper) and keep everything else (like exchange rates) as doubles?将钱长期存放(或在包装内)并将其他所有内容(如汇率)保持为双倍是否总是安全的? In other words, won't I run into basically the same issues as having everything in doubles if I do Math.round(money * rate) (money being cents and rate being a double)?换句话说,如果我做Math.round(money * rate) (钱是美分,费率是双倍),我会不会遇到与双打基本相同的问题?

  2. FastMoney and many other libs only support operations between them and primitive types. FastMoney 和许多其他库只支持它们和原始类型之间的操作。 How am I supposed to get an accurate representation of let's say the return of an investment if I can't do profit.divide(investment) (both being FastMoney).如果我不能做profit.divide(investment) (都是FastMoney),我应该如何准确表示profit.divide(investment) I guess the idea is I convert both to doubles and then divide them, but that would be inaccurate right?我想这个想法是我将两者都转换为双打然后将它们分开,但这不准确吗?

The functionality you are looking for is already implemented in the JavaMoney Library.您正在寻找的功能已在 JavaMoney 库中实现。

It has a FastMoney class that does long arithmetic which is exactly what you have asked for.它有一个 FastMoney 类,可以进行long算术,这正是您所要求的。

For New Java Developers - Why long and not double?对于新的 Java 开发人员 - 为什么要长而不是加倍?

Floating point arithmetic in Java leads to some unexpected errors in precision due to their implementation. Java 中的浮点运算由于其实现而导致一些意外的精度错误。 Hence it is not recommended in financial calculations.因此,不建议在财务计算中使用它。

Also note that this is different from the precision loss in long arithmetic calculations which is due to the fractional portion not being stored in the long.另请注意,这与long算术计算中的精度损失不同,这是由于小数部分未存储在 long 中。 This can be prevented during implementation by moving the fractional portion to another long (eg 1.05 -> 1 dollar and 5 cents).这可以在实施过程中通过将小数部分移动到另一个多头(例如 1.05 -> 1 美元和 5 美分)来防止。

References参考

  1. A Quick Tutorial快速教程

  2. Project Website项目网站

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM