Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++ equivalent to Java's BigDecimal?

Tags:

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.

like image 621
poindexter Avatar asked Jan 25 '11 21:01

poindexter


People also ask

What can I use instead of BigDecimal?

If you need to use division in your arithmetic, you need to use double instead of BigDecimal.

Which is more accurate BigDecimal or double?

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.

How accurate is BigDecimal?

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.


1 Answers

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); 
like image 167
Konrad Rudolph Avatar answered Sep 22 '22 18:09

Konrad Rudolph