I'm looking for a C++ class that can do decimal floating point arithmetic. Looking through http://speleotrove.com/decimal/ there are links to all sorts of classes that people have written and not maintained. Digging through the decNumber++ stuff led me to some emails showing that GCC will eventually support this functionality. (Formally known as ISO/IEC TR 24733)
I'm looking for something I can use as a drop-in replacement for float or double, something that other people are using in their own projects. Hopefully open source.
Thanks!
EDIT: I should point out that I'm trying to use this to represent prices. So I need EXACT decimals, not HUGE decimals.
If you need to use division in your arithmetic, you need to use double instead of BigDecimal.
A BigDecimal is an accurate way of expressing numbers. A Double has a reliable accuracy. Going with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could occur in the 0.001 being dropped collectively when summing as the variation in magnitude is so large. With BigDecimal this would not occur.
This limits it to 15 to 17 decimal digits of accuracy. BigDecimal can grow to any size you need it to. Double operates in binary which means it can only precisely represent numbers which can be expressed as a finite number in binary. For example, 0.375 in binary is exactly 0.011.
There exists a huge library called GMP (GNU multiple precision library) which supports this and also has C++ bindings, though to be honest the C++ interface is a bit wonky and outdated.
An example from the documentation, the following creates a float called f
with at least 500 bits of precision:
mpf_class f(1.5, 500);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With