On Monday, 20 May 2019 at 11:10:32 UTC, Boqsc wrote:
https://dlang.org/spec/float.html

I'm frozen in learning basics of D lang since I want to create a simple game and I really would like a clean and simple code, however to me floating points are magic.

https://wiki.dlang.org/Review_Queue
Since std.decimal is still work in progress and apparently its development is stuck for a while, should I just somehow use floating point to store currency or wait until Decimal package will be finally included into std Phobos of D lang?

For a simple game storing money in cents, as an int or long, is perfectly fine.

If you're worried that $92_233_720_368_547_758.07 (long.max) is not enough money for your game, I'd note that the entire current world economy is about a thousandth of that. Even so, there's std.bigint.BigInt, which has no set limit, and can in theory represent every whole number up to about 256^(2^64), or about 4 quintillion digits. You will encounter other problems before this limit becomes an issue.

Depending on the scale and required accuracy, you could also perfectly well use doubles. Doubles can accurately represent up to about half the world economy in cents. There are some caveats when using doubles, as floating-point math is not always equal to regular math. For instance, if you had the entire world economy in one variable, you could subtract a cent at a time without the variable decreasing. If these cents were simultaneously added to a different variable (to represent a transaction), this would be an infinite source of money. In the same vein, it's possible for (a+b) != ((a-x)+(b+x)) if a and b are wildly different in size. For a game, this is very unlikely to be a problem, but would certainly be worth considering for a real-world application.

For almost every application, a long representing the number of cents should cover almost every situation, and is very easy to reason about, so I would definitely recommend that. This decision could cause overflow issues in some rare cases, and calculating interest on extreme values could be slightly inaccurate depending on how you do it, but those situations are extreme enough that you can reasonably expect them to never happen.

The one case where floating-point almost invariably will enter the picture is foreign exchange - the value of one unit of one currency in some other currency will only very rarely be a whole number.

--
  Simen

Reply via email to