简体   繁体   中英

What is the recommended data type for handling Money (just 2-decimal places) in Elixir/Erlang?

What is the recommended data type for handling Money - numeric values with just 2-decimal places in Elixir/Erlang?

I think you should always use integers when handling money. Floating point operations can have rounding errors and money-handling code that's off even by 1 cent is often not ok. For example, instead of

amount = 99.99

Use

amount_cents = 9999

This is doubly important if you are storing the amount in a database since conversion between Elixir and your database and back may produce undesirable results.

I highly recommend using the Decimal library. There has been a lot of thought and work put into handling all the difficult edge cases.

Money, like cryptography, is not something you should implement yourself. You will get it wrong.

Using the Decimal library is the way to go in currency handling logic, especially when you have to perform arithmetic operations with the quantities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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