Reputation:
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
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
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
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:
long float
https://ginac.de/CLN/float precision<N>
http://www.hvks.com/Numerical/arbitrary_precision.html <- This one actually contains an example for printing out pi (to std::string
), which seems to be what you're looking forUpvotes: 1