Sobes.tech
Junior

How can monetary equivalents be stored using the int data type?

sobes.tech AI

Answer from AI

It is possible to store monetary equivalents using the lower bits of type int for the fractional part. The most common way is to store the amount in the smallest possible unit (for example, kopecks for rubles, cents for dollars).

Example:

An amount of $123.45 can be represented as 12345 kopecks.

int rubles = 123;
int kopecks = 45;
int total_kopecks = rubles * 100 + kopecks; // 12345

or directly:

int total_kopecks = 12345;

When performing operations:

Addition:

int amount1 = 12345; // $123.45
int amount2 = 6789;  // $67.89
int sum = amount1 + amount2; // 19134 (equivalent to $191.34)

Subtraction:

int amount1 = 12345; // $123.45
int amount2 = 6789;  // $67.89
int diff = amount1 - amount2; // 5556 (equivalent to $55.56)

To output and convert back to rubles/dollars:

int total_kopecks = 19134;
int rubles_part = total_kopecks / 100; // 191
int kopecks_part = total_kopecks % 100; // 34
// Result: 191.34

Advantages:

  • Avoids precision issues inherent in floating-point types (float, double).
  • Operations (addition, subtraction) are fast and accurate.

Disadvantages:

  • Limited range of int. For large sums or currencies with high unit value, long long may be required.
  • Multiplication and division require caution to avoid losing precision. For example, when calculating percentages.

Example of percentage calculation:

int principal = 100000; // 1000.00 rubles
double rate = 0.05;     // 5%
// Incorrect approach:
// int interest = principal * rate; // Loss of precision
// Correct approach (multiply first, then divide):
int interest = principal * 5 / 100; // 5000 (equivalent to 50.00 rubles)
// Or using another representation of the rate:
int rate_permil = 50;   // 50 per mille (0.05)
int interest_permil = principal * rate_permil / 1000; // 5000

This method is suitable for most financial calculations where high precision is required with relatively simple arithmetic operations. For more complex scenarios involving rounding rules, different currencies, and their exchange rates, specialized libraries or data types (e.g., decimal in other languages, or custom implementations) may be necessary.