Is there a way to use decimal data types such as decimal32
, decimal64
or decimal128
in my C++ programs?
The decimal data type is an exact numeric data type defined by its precision (total number of digits) and scale (number of digits to the right of the decimal point).
The C language provides the four basic arithmetic type specifiers char, int, float and double, and the modifiers signed, unsigned, short, and long. The following table lists the permissible combinations in specifying a large set of storage size-specific declarations.
Most of the time, for small programs, we use the basic fundamental data types in C – int, char, float, and double. For more complex and huge amounts of data, we use derived types – array, structure, union, and pointer.
Types of Data Types in CFloating-point, integer, double, character. Union, structure, array, etc. The basic data types are also known as the primary data types in C programming.
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.
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"
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