Décimales arbitraires précision en C # [double]
Question
Doublons possibles: Big Les entiers
C # chiffres décimaux significatifs illimités (précision arbitraire) sans java
Je lis la question à décimales de précision arbitraire en C #? mais je n » t ont la bibliothèque J #. J'ai besoin d'une bibliothèque pour les décimales de précision arbitraire avec C #.
La solution
Big Decimal:
- Installer le J # l'exécution (il est gratuit): http://www.microsoft.com/downloads/en/details.aspx?familyid=f72c74b3-ed0e-4af8-ae63-2f0e42501be1&displaylang=en
Big Int (Si vous aimez la solution de J.D. ou si vous voulez venir avec une classe de type nombre / fraction rationnelle, et je manqué en quelque sorte que vous cherchiez décimaux, pas ints.):
- Get C # 4.0: entiers Big C #
- Obtenir la classe IntX: http://intx.codeplex.com/
Autres conseils
Vous pourriez mettre en œuvre votre propre basé sur la classe BigInteger de .NET 4.0. Je l'ai fait pour le plaisir, il ne multiplication que:
public struct BigDecimal {
public BigInteger Integer { get; set; }
public BigInteger Scale { get; set; }
public BigDecimal(BigInteger integer, BigInteger scale) : this() {
Integer = integer;
Scale = scale;
while (Scale > 0 && Integer % 10 == 0) {
Integer /= 10;
Scale -= 1;
}
}
public static implicit operator BigDecimal(decimal a) {
BigInteger integer = (BigInteger)a;
BigInteger scale = 0;
decimal scaleFactor = 1m;
while ((decimal)integer != a * scaleFactor) {
scale += 1;
scaleFactor *= 10;
integer = (BigInteger)(a * scaleFactor);
}
return new BigDecimal(integer, scale);
}
public static BigDecimal operator *(BigDecimal a, BigDecimal b) {
return new BigDecimal(a.Integer * b.Integer, a.Scale + b.Scale);
}
public override string ToString() {
string s = Integer.ToString();
if (Scale != 0) {
if (Scale > Int32.MaxValue) return "[Undisplayable]";
int decimalPos = s.Length - (int)Scale;
s = s.Insert(decimalPos, decimalPos == 0 ? "0." : ".");
}
return s;
}
}
...
decimal d1 = 254727458263237.1356246819m;
decimal d2 = 991658834219519273.110324m;
// MessageBox.Show((d1 * d2).ToString()); // OverflowException
BigDecimal bd1 = d1;
BigDecimal bd2 = d2;
MessageBox.Show((bd1 * bd2).ToString()); // 252602734305022989458258125319270.5452949161059356
Il y a toujours wrapper GNU MP pour .NET aussi longtemps que vous ne me dérange pas en utilisant le GMP .