Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact decimal datatype for C++?

Tags:

PHP has a decimal type, which doesn't have the "inaccuracy" of floats and doubles, so that 2.5 + 2.5 = 5 and not 4.999999999978325 or something like that.

So I wonder if there is such a data type implementation for C or C++?

like image 957
dtech Avatar asked Mar 10 '13 07:03

dtech


People also ask

Does C have a decimal type?

The decimal data type is an extension of the ANSI C language definition.

What is the data type for a decimal?

Decimal is not a floating-point data type. The Decimal structure holds a binary integer value, together with a sign bit and an integer scaling factor that specifies what portion of the value is a decimal fraction.

What is precision value in C?

So, precision means the number of digits mentioned after the decimal point in the float number. For example, the number 2.449561 has precision six, and -1.058 has precision three.


2 Answers

The Boost.Multiprecision library has a decimal based floating point template class called cpp_dec_float, for which you can specify any precision you want.

#include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>

int main()
{
    namespace mp = boost::multiprecision;
    // here I'm using a predefined type that stores 100 digits,
    // but you can create custom types very easily with any level
    // of precision you want.
    typedef mp::cpp_dec_float_100 decimal;

    decimal tiny("0.0000000000000000000000000000000000000000000001");
    decimal huge("100000000000000000000000000000000000000000000000");
    decimal a = tiny;         

    while (a != huge)
    {
        std::cout.precision(100);
        std::cout << std::fixed << a << '\n';
        a *= 10;
    }    
}
like image 68
Benjamin Lindley Avatar answered Sep 19 '22 13:09

Benjamin Lindley


Yes:

There are arbitrary precision libraries for C++.
A good example is The GNU Multiple Precision arithmetic library.

like image 20
Martin York Avatar answered Sep 19 '22 13:09

Martin York