Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Visual C++ rounding issue for currency data

In my financial related application, Double use as the data type for currency data. but recently I found Double having issue while rounding.

As example inside a double variable
35.25 stored as 35.249999999999999999999 35.75 stored as 35.750000000000000000001

so when does it trying to round the number to one decimal point 35.25 = 35.3 35.75 = 35.8

It means one number round to ceiling other to floor.

  1. Could anybody suggest a solution for this issue?

  2. What is the suitable data type should use for currency data in Visual C++

Upvotes: 3

Views: 771

Answers (2)

foraidt
foraidt

Reputation: 5689

Your problem is not rounding. It is how floating point values are represented in the computer.

This is why double is not suited very well for currency related calculations.
As @Mysticial recommended, you might try using int and use Cents instead of Dollars or Euros as unit for your calculations.

This way addition, subtraction and multiplication should work as expected. You will have to take care of division operations though, as these will result in any decimal parts of the quotient being cut off, i.e. always rounded down.

The logic for converting the values into human readable units like Euros and Dollars can be entirely a matter of the user interface so only when displaying you have to take care of converting from Cents to Euros.

Sample

Here's a sample demonstrating the absence of precision loss.

int a = 25;             //  0.25 eurodollars
int b = 1000;           // 10.00 ED
int sum = a + b;        // 10.25 ED
int difference = b - a; //  9.75 ED

Upvotes: 3

Blake7
Blake7

Reputation: 2235

The IEEE-754 defines different data types as having different levels of significant digits.

For example the IEEE-754 defines a double as only having a 15.95 decimal digitis of precision.

So one option is make sure you stay within the maximum precision by rounding the final value to a number of significant digits that is less than this maximum limit.

But how you round is generally pre-defined by the type of finacial calculation you are doing.

For example FX spot prices are generally quoted to 4 deciml places and rates are quoted to 7 decimal places.

So without more information in what type of calculation you are doing it is a little hard to offer a solution.

Upvotes: 6

Related Questions