user14532470
user14532470

Reputation:

What's the C++ equivalent of C#'s decimal type?

I like decimal in many of my C# programs and I want to try it in other C languages.

I wrote this code in C#:

using System;

decimal get_pi();

int main() {
    Console.WriteLine("Give a number ranging from 1-100: ");
    decimal num = Console.ReadLine();
    Console.Write("Algebraic Equivalent: ");
    if (num >= get_pi()) {
        Console.WriteLine("π");
    } else {
        Console.WriteLine(num);
    }
    // Currently updating the program for giving algebraic equivalents
}

And I want to rewrite it in C++.

I realized that in both C and C++, they have no exact equivalent to the decimal type, and best you can use is double, but the fact that there's actually a supported decimal type in C (based on Is there a C equivalent of C#'s decimal type?), it got me curious if there is also an equivalent in C++.

Is there any C# decimal type equivalent in C++ or is double the best choice instead?

Upvotes: 2

Views: 3448

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74257

There is not, though I believe there's a proposal out there.

But if you navigate over to IBM Fellow Mike Cowlishaw's page General Decimal Arithmetic, you'll

  • Learn more than you ever wanted to know about the topic — he pretty much wrote the IEEE 754 specification for decimal floating point — and
  • Get a link to an ANSI C implementation of it

For what it's worth, the .Net source code is open-source and on Github. If you wanted to port System.Decimal from C# to C++, you could start here:

Upvotes: 6

nada
nada

Reputation: 2117

C#'s decimal type is actually just a so called arbitrary precision float with the word arbitrary switched out with a fixed value, which can be looked up in its source (already linked by that answer). It's 28 significant digits.

Arbitrary precision floats are not included in at least C++20's standard library, but there are quite a number of libraries out there, which include that functionality. C#'s decimal is also part of the .NET library, which is strictly speaking also a library and not part of the language itself (but very tightly coupled).

Examples for libraries supporting arbitrary precision floats for C++ include:

Upvotes: 1

Related Questions