Is int64_t enough for banking? If not what are the alternatives?

166 Views Asked by At

I am writing a personal finance cli in C and I want to make sure that it can handle the commodity sizes in real world and still be very performant.

The struct that holds the value is structured like this,

typedef struct {
  int64_t before_decimal; // 9 pentillion before decimal
  uint32_t after_decimal; // 4 billion after decimal
} ledger_commodity_t;

int64_t has a range of -2^63 to 2^63-1 (9 pentillion) which I think is enough, even if one chooses to process our entire economy for some reason. And I assume using a BigInt is a waste of processing power in this particular case since it's possible to predict the range.

Or am I wrong in assuming that?

Wrapping silently is not an issue, as I'll will be the one parsing the ledger file, and will be able to throw an error if it happens.

libzahl, gmp, TomsFastMath, etc all look good, but I would rather avoid using any library, as I be only adding and subtracting within the range of global economy.

2

There are 2 best solutions below

1
Gyro Gearloose On

As the example of the Iranian rial given by @JohnFilleau shows, int64_t might be just a little too small.

As you have an uint32_t for the after decimal part, my recommendation would be to use that, and a currency dependent constant on how many digits/bits are shifted to that value.

0
chux - Reinstate Monica On

With the next version of C (C2X, C24 or whatever), look to using optional decimal floating point types such as decimal64 for money.