Rounding floats inaccurate

We have a problem with rounding floating point numbers for some financial calculations.

Basically, we want to round monetary amounts, for example, from 1,000,000,000,555 to 2 decimal places. However, the float representation of this number is 1,000,000,000.554,9999, and as a result, we round up to 1,000,000,000.55 instead of the correct 1,000,000,000.56.

Is there any way to solve this problem in a safe way? The only thing that we have come up with so far is to always add the smallest represented float to the amount before the rounding operation, but we do not know if this is safe in all cases.

The code is written in C and should run on windows32 / 64 / linux / solaris, so we, unfortunately, do not have access to good materials, such as the decimal data type in .net.

Any input would be helpful.

Thanks Ricard

+3
source share
4 answers

The correct way to represent currencies most often uses integers. For example, in the eurozone, the general approach is to present values ​​in micro-euros (1E-6). Obviously, you used 64-bit math for this. You will always use this throughout the application. Only on human input would you round, and you would do this by dividing by 10,000 to get the whole amount in cents.

+10
source

, , !

, . 3,1445217 . 17 ( , !), .

, , , 5 , 5 , .. CHF 3.14, CHF 3.15 CHF 3.10 , , 3.10 3.15 .

. BigDecimal, . , , .

- , .. 55 35 11070 , .

, -. -, , 40 , .

+5
+4

Windows C/++.

decimal class. MSDN

, .

C/++, , decNumber.

In both cases, you should have many unit and integration tests that cover corner cases with rounding. They will hurt you. Rounding also hides other errors very well.

However, as others have said, be very careful when you are round. For example, in the UK income tax software specification, about half of the text is about where and how (differently in each place) to round numbers, since you need to get the same results using a manual tax table.

0
source

Source: https://habr.com/ru/post/1715968/


All Articles