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

后端 未结 8 1791
逝去的感伤
逝去的感伤 2020-11-27 19:42

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 peop

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 20:07

    I may be too late for this but would 128bit decimals work? These have been accepted into C++ and at least gcc has them since gcc-4.5 (we're starting 4.9 now:

    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
      {
        std::decimal::decimal32 dn(.3), dn2(.099), dn3(1000), dn4(201);
        dn-=dn2;
        dn*=dn3;
        cout << "decimal32 = "  << (dn==dn4) << " : " << decimal32_to_double(dn) << endl;
      }
    
      {
        std::decimal::decimal64 dn(.3), dn2(.099), dn3(1000), dn4(201);
        dn-=dn2;
        dn*=dn3;
        cout << "decimal64 = "  << (dn==dn4) << " : " << decimal64_to_double(dn) << endl;
      }
    
      {
        std::decimal::decimal128 dn(.3), dn2(.099), dn3(1000), dn4(201);
        dn-=dn2;
        dn*=dn3;
        cout << "decimal128 = " << (dn==dn4) << " : " << decimal128_to_double(dn) << endl;
      }
    
      return 0;
    }
    

    Note there is decimal32 equal in size to float, decimal64 equal in size to most double. So decimal128 is pretty big. From Wikipedia: Decimal128 supports 34 decimal digits of significand and an exponent range of −6143 to +6144, i.e. ±0.000000000000000000000000000000000×10−6143 to ±9.999999999999999999999999999999999×106144. (Equivalently, ±0000000000000000000000000000000000×10−6176 to ±9999999999999999999999999999999999×106111.)

    The mpfr library is arbitrary precision binary floating point - not arbitrary precision decimal. There is a difference.

提交回复
热议问题