Visual C ++ rounding problem for currency data
In my finance related application, dual use as data type for currency data. but I recently discovered that Double has rounding problems.
As an example, inside a double variable
35.25 is stored as 35.249999999999999999999 35.75 is stored as 35.750000000000000000001
so when it tries to round the number to one decimal point 35.25 = 35.3 35.75 = 35.8
This means one number from floor to ceiling.

Can anyone suggest a solution to this problem?

What is the appropriate data type to use for currency data in Visual C ++
source to share
IEEE754 defines different data types as having different significant digit levels.
For example, IEEE754 defines a double variant because it has a precision of 10.95 decimal digits.
So one option is to make sure you stay within the maximum precision by rounding the final value to a few significant digits that are less than this maximum limit.
But how you are usually predetermined by the type of final calculation you do.
For example, foreign exchange spot prices are usually quoted in 4 decimeter locations, and rates are quoted up to 7 decimal places.
So, without further information on what calculation you are doing, it is a bit difficult to come up with a solution.
source to share
Your problem is not rounding up. how floating point values are represented on a computer.
This is why double
it is not suitable for currencyrelated settlements.
As @Mysticial recommends you can try int
and use Cents instead of Dollars or Euros as the unit for your calculations.
So addition, subtraction, and multiplication should work as expected. You will have to take care of the divisions, although they will cause any decimal parts to be cut off, i.e. Always rounded down.
The logic for converting values to human readable units such as euros and dollars can be completely tied to the user interface, so only when displaying do you need to take care of the conversion from cents to euros.
Example
Here is a sample showing no loss accuracy.
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
source to share