C++ decimal data types

59,936

Solution 1

The classes from the Decimal TR are not implemented for all compilers. Some compilers, e.g., gcc, implement the C Decimal TR and provide the corresponding extensions in C++, too. In the past there was an open source implementation for the C++ Decimal TR available but I failed to locate it. If your compiler doesn't support the decimal types, your best option is probably to create a wrapper for IBM's decNumber library.

To improve the situation in the future of C++, I have created a plan to update the TR and I'm going to turn the current TR into a complete proposal ready for the next C++ committee meeting (in April in Bristol), trying to get it adopted into the C++ standard, possibly into the revision planned for 2014. The implementation I have is part of my regular work and it isn't up to me to decide whether it is can be made available publically although there is some hope that it can be open sourced at some point.

Solution 2

You can use easy to use header-only solution for C++ with templates: https://github.com/vpiotr/decimal_for_cpp

Notice that this is not a *Big*Decimal class; it is limited to 64 bits' worth of "mantissa" digits.

[taken from link]

  #include "decimal.h"

  using namespace dec;

  // the following declares currency variable with 2 decimal points
  // initialized with integer value (can be also floating-point)
  decimal<2> value(143125);

  // to use non-decimal constants you need to convert them to decimal
  value = value / decimal_cast<2>(333.0);

  // output values
  cout << "Result is: " << value << endl;
  // this should display something like "429.80"

  // to mix decimals with different precision use decimal_cast
  decimal<6> exchangeRate(12.1234);
  value = decimal_cast<2>(decimal_cast<6>(value) * exchangeRate);

  cout << "Result 2 is: " << value << endl;
  // this should display something like "5210.64"

  cout << "Result 2<6> is: " << decimal_cast<6>(value) << endl;
  // this should display something like "5210.640000"

Solution 3

use an int32 or int64, and (manually) shift the decimal point to where you want it to be. If you're measuring dollars, for example, just measure cents instead and display the value differently. simple!

Solution 4

Boost has cpp_dec_float as well. That's probably the best solution until it's adopted into the standard.

https://www.boost.org/doc/libs/1_68_0/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_dec_float.html

EDIT: This library uses floating point values in the implementation so is not a true decimal math library IMO.

Share:
59,936
fpiro07
Author by

fpiro07

Updated on October 06, 2020

Comments

  • fpiro07
    fpiro07 over 3 years

    Is there a way to use decimal data types such as decimal32, decimal64 or decimal128in my C++ programs?