Hi, I am calculating arithmetic mean of some $ values, so my numbers should have dollar part and cent part ( two decimal points )
double x = 3.46;
double y = 12. 13;
double arithmeticMean = ( x + y ) / 2; //7.795...should be 7.80
I don't care for stream output, I need to have correct values in memory ( in variable arithmeticMean ).
7.80....arithmeticMean / 2 = 3.9
7.795...arithmeticMean / 2 = 3.8975 //wrong

You will never get exact precision with floating point because of the way they are represented in memory.

3.8975 //wrong

If you round that to two decimals it will be "correct"(see Ancient Dragon)
Do all your floating calculations and start rounding afterwards.
When money is involved, the decimal type was invented for it.

For money, it might be better to use large integers instead of floats to avoid the rounding errors. Just use an implied decimal point, for example 100 is $1.00 USD. Or you could use two integers, one for cents and the other for whole dollars, but the math would be a little more complicated.

Thanks for the advise. But in an Ancient time I had to devise a decimal type for the company I was working for in Modula-2. That was not a managed language either. So with a little effort one should be able to succeed in devising a decimal type class even in unmanaged C++.

1. There are lots of fixed decimal/currency class libraries for C and C++: search Google.
2. What's a problem? Calculate all values in cents (use double type, don't forget floor and ceil library functions, Banker rounding method etc). Some year ago I have wrote ~100000 LOC of financial codes with double arithmetics. No cents were lost till now ;)...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.