Decimal.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Buffers.Binary;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Runtime.CompilerServices;
  8. using System.Runtime.InteropServices;
  9. using System.Runtime.Serialization;
  10. namespace System
  11. {
  12. // Implements the Decimal data type. The Decimal data type can
  13. // represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
  14. // 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
  15. // Decimal data type is ideally suited to financial calculations that
  16. // require a large number of significant digits and no round-off errors.
  17. //
  18. // The finite set of values of type Decimal are of the form m
  19. // / 10e, where m is an integer such that
  20. // -296 <; m <; 296, and e is an integer
  21. // between 0 and 28 inclusive.
  22. //
  23. // Contrary to the float and double data types, decimal
  24. // fractional numbers such as 0.1 can be represented exactly in the
  25. // Decimal representation. In the float and double
  26. // representations, such numbers are often infinite fractions, making those
  27. // representations more prone to round-off errors.
  28. //
  29. // The Decimal class implements widening conversions from the
  30. // ubyte, char, short, int, and long types
  31. // to Decimal. These widening conversions never loose any information
  32. // and never throw exceptions. The Decimal class also implements
  33. // narrowing conversions from Decimal to ubyte, char,
  34. // short, int, and long. These narrowing conversions round
  35. // the Decimal value towards zero to the nearest integer, and then
  36. // converts that integer to the destination type. An OverflowException
  37. // is thrown if the result is not within the range of the destination type.
  38. //
  39. // The Decimal class provides a widening conversion from
  40. // Currency to Decimal. This widening conversion never loses any
  41. // information and never throws exceptions. The Currency class provides
  42. // a narrowing conversion from Decimal to Currency. This
  43. // narrowing conversion rounds the Decimal to four decimals and then
  44. // converts that number to a Currency. An OverflowException
  45. // is thrown if the result is not within the range of the Currency type.
  46. //
  47. // The Decimal class provides narrowing conversions to and from the
  48. // float and double types. A conversion from Decimal to
  49. // float or double may loose precision, but will not loose
  50. // information about the overall magnitude of the numeric value, and will never
  51. // throw an exception. A conversion from float or double to
  52. // Decimal throws an OverflowException if the value is not within
  53. // the range of the Decimal type.
  54. [StructLayout(LayoutKind.Sequential)]
  55. [Serializable]
  56. [System.Runtime.Versioning.NonVersionable] // This only applies to field layout
  57. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  58. public readonly partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable<decimal>, IEquatable<decimal>, IDeserializationCallback, ISpanFormattable
  59. {
  60. // Sign mask for the flags field. A value of zero in this bit indicates a
  61. // positive Decimal value, and a value of one in this bit indicates a
  62. // negative Decimal value.
  63. //
  64. // Look at OleAut's DECIMAL_NEG constant to check for negative values
  65. // in native code.
  66. private const int SignMask = unchecked((int)0x80000000);
  67. // Scale mask for the flags field. This byte in the flags field contains
  68. // the power of 10 to divide the Decimal value by. The scale byte must
  69. // contain a value between 0 and 28 inclusive.
  70. private const int ScaleMask = 0x00FF0000;
  71. // Number of bits scale is shifted by.
  72. private const int ScaleShift = 16;
  73. // Constant representing the Decimal value 0.
  74. public const decimal Zero = 0m;
  75. // Constant representing the Decimal value 1.
  76. public const decimal One = 1m;
  77. // Constant representing the Decimal value -1.
  78. public const decimal MinusOne = -1m;
  79. // Constant representing the largest possible Decimal value. The value of
  80. // this constant is 79,228,162,514,264,337,593,543,950,335.
  81. public const decimal MaxValue = 79228162514264337593543950335m;
  82. // Constant representing the smallest possible Decimal value. The value of
  83. // this constant is -79,228,162,514,264,337,593,543,950,335.
  84. public const decimal MinValue = -79228162514264337593543950335m;
  85. // The lo, mid, hi, and flags fields contain the representation of the
  86. // Decimal value. The lo, mid, and hi fields contain the 96-bit integer
  87. // part of the Decimal. Bits 0-15 (the lower word) of the flags field are
  88. // unused and must be zero; bits 16-23 contain must contain a value between
  89. // 0 and 28, indicating the power of 10 to divide the 96-bit integer part
  90. // by to produce the Decimal value; bits 24-30 are unused and must be zero;
  91. // and finally bit 31 indicates the sign of the Decimal value, 0 meaning
  92. // positive and 1 meaning negative.
  93. //
  94. // NOTE: Do not change the order in which these fields are declared. The
  95. // native methods in this class rely on this particular order.
  96. // Do not rename (binary serialization).
  97. private readonly int flags;
  98. private readonly int hi;
  99. private readonly int lo;
  100. private readonly int mid;
  101. // Constructs a Decimal from an integer value.
  102. //
  103. public Decimal(int value)
  104. {
  105. if (value >= 0)
  106. {
  107. flags = 0;
  108. }
  109. else
  110. {
  111. flags = SignMask;
  112. value = -value;
  113. }
  114. lo = value;
  115. mid = 0;
  116. hi = 0;
  117. }
  118. // Constructs a Decimal from an unsigned integer value.
  119. //
  120. [CLSCompliant(false)]
  121. public Decimal(uint value)
  122. {
  123. flags = 0;
  124. lo = (int)value;
  125. mid = 0;
  126. hi = 0;
  127. }
  128. // Constructs a Decimal from a long value.
  129. //
  130. public Decimal(long value)
  131. {
  132. if (value >= 0)
  133. {
  134. flags = 0;
  135. }
  136. else
  137. {
  138. flags = SignMask;
  139. value = -value;
  140. }
  141. lo = (int)value;
  142. mid = (int)(value >> 32);
  143. hi = 0;
  144. }
  145. // Constructs a Decimal from an unsigned long value.
  146. //
  147. [CLSCompliant(false)]
  148. public Decimal(ulong value)
  149. {
  150. flags = 0;
  151. lo = (int)value;
  152. mid = (int)(value >> 32);
  153. hi = 0;
  154. }
  155. // Constructs a Decimal from a float value.
  156. //
  157. public Decimal(float value)
  158. {
  159. DecCalc.VarDecFromR4(value, out AsMutable(ref this));
  160. }
  161. // Constructs a Decimal from a double value.
  162. //
  163. public Decimal(double value)
  164. {
  165. DecCalc.VarDecFromR8(value, out AsMutable(ref this));
  166. }
  167. //
  168. // Decimal <==> Currency conversion.
  169. //
  170. // A Currency represents a positive or negative decimal value with 4 digits past the decimal point. The actual Int64 representation used by these methods
  171. // is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900.
  172. //
  173. public static decimal FromOACurrency(long cy)
  174. {
  175. ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue.
  176. bool isNegative = false;
  177. if (cy < 0)
  178. {
  179. isNegative = true;
  180. absoluteCy = (ulong)(-cy);
  181. }
  182. else
  183. {
  184. absoluteCy = (ulong)cy;
  185. }
  186. // In most cases, FromOACurrency() produces a Decimal with Scale set to 4. Unless, that is, some of the trailing digits past the decimal point are zero,
  187. // in which case, for compatibility with .Net, we reduce the Scale by the number of zeros. While the result is still numerically equivalent, the scale does
  188. // affect the ToString() value. In particular, it prevents a converted currency value of $12.95 from printing uglily as "12.9500".
  189. int scale = 4;
  190. if (absoluteCy != 0) // For compatibility, a currency of 0 emits the Decimal "0.0000" (scale set to 4).
  191. {
  192. while (scale != 0 && ((absoluteCy % 10) == 0))
  193. {
  194. scale--;
  195. absoluteCy /= 10;
  196. }
  197. }
  198. return new decimal((int)absoluteCy, (int)(absoluteCy >> 32), 0, isNegative, (byte)scale);
  199. }
  200. public static long ToOACurrency(decimal value)
  201. {
  202. return DecCalc.VarCyFromDec(ref AsMutable(ref value));
  203. }
  204. private static bool IsValid(int flags) => (flags & ~(SignMask | ScaleMask)) == 0 && ((uint)(flags & ScaleMask) <= (28 << ScaleShift));
  205. // Constructs a Decimal from an integer array containing a binary
  206. // representation. The bits argument must be a non-null integer
  207. // array with four elements. bits[0], bits[1], and
  208. // bits[2] contain the low, middle, and high 32 bits of the 96-bit
  209. // integer part of the Decimal. bits[3] contains the scale factor
  210. // and sign of the Decimal: bits 0-15 (the lower word) are unused and must
  211. // be zero; bits 16-23 must contain a value between 0 and 28, indicating
  212. // the power of 10 to divide the 96-bit integer part by to produce the
  213. // Decimal value; bits 24-30 are unused and must be zero; and finally bit
  214. // 31 indicates the sign of the Decimal value, 0 meaning positive and 1
  215. // meaning negative.
  216. //
  217. // Note that there are several possible binary representations for the
  218. // same numeric value. For example, the value 1 can be represented as {1,
  219. // 0, 0, 0} (integer value 1 with a scale factor of 0) and equally well as
  220. // {1000, 0, 0, 0x30000} (integer value 1000 with a scale factor of 3).
  221. // The possible binary representations of a particular value are all
  222. // equally valid, and all are numerically equivalent.
  223. //
  224. public Decimal(int[] bits)
  225. {
  226. if (bits == null)
  227. throw new ArgumentNullException(nameof(bits));
  228. if (bits.Length == 4)
  229. {
  230. int f = bits[3];
  231. if (IsValid(f))
  232. {
  233. lo = bits[0];
  234. mid = bits[1];
  235. hi = bits[2];
  236. flags = f;
  237. return;
  238. }
  239. }
  240. throw new ArgumentException(SR.Arg_DecBitCtor);
  241. }
  242. // Constructs a Decimal from its constituent parts.
  243. //
  244. public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
  245. {
  246. if (scale > 28)
  247. throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
  248. this.lo = lo;
  249. this.mid = mid;
  250. this.hi = hi;
  251. flags = ((int)scale) << 16;
  252. if (isNegative)
  253. flags |= SignMask;
  254. }
  255. void IDeserializationCallback.OnDeserialization(object? sender)
  256. {
  257. // OnDeserialization is called after each instance of this class is deserialized.
  258. // This callback method performs decimal validation after being deserialized.
  259. if (!IsValid(flags))
  260. throw new SerializationException(SR.Overflow_Decimal);
  261. }
  262. // Constructs a Decimal from its constituent parts.
  263. private Decimal(int lo, int mid, int hi, int flags)
  264. {
  265. if (IsValid(flags))
  266. {
  267. this.lo = lo;
  268. this.mid = mid;
  269. this.hi = hi;
  270. this.flags = flags;
  271. return;
  272. }
  273. throw new ArgumentException(SR.Arg_DecBitCtor);
  274. }
  275. private Decimal(in decimal d, int flags)
  276. {
  277. this = d;
  278. this.flags = flags;
  279. }
  280. // Returns the absolute value of the given Decimal. If d is
  281. // positive, the result is d. If d is negative, the result
  282. // is -d.
  283. //
  284. internal static decimal Abs(in decimal d)
  285. {
  286. return new decimal(in d, d.flags & ~SignMask);
  287. }
  288. // Adds two Decimal values.
  289. //
  290. public static decimal Add(decimal d1, decimal d2)
  291. {
  292. DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), false);
  293. return d1;
  294. }
  295. // Rounds a Decimal to an integer value. The Decimal argument is rounded
  296. // towards positive infinity.
  297. public static decimal Ceiling(decimal d)
  298. {
  299. int flags = d.flags;
  300. if ((flags & ScaleMask) != 0)
  301. DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToPositiveInfinity);
  302. return d;
  303. }
  304. // Compares two Decimal values, returning an integer that indicates their
  305. // relationship.
  306. //
  307. public static int Compare(decimal d1, decimal d2)
  308. {
  309. return DecCalc.VarDecCmp(in d1, in d2);
  310. }
  311. // Compares this object to another object, returning an integer that
  312. // indicates the relationship.
  313. // Returns a value less than zero if this object
  314. // null is considered to be less than any instance.
  315. // If object is not of type Decimal, this method throws an ArgumentException.
  316. //
  317. public int CompareTo(object? value)
  318. {
  319. if (value == null)
  320. return 1;
  321. if (!(value is decimal))
  322. throw new ArgumentException(SR.Arg_MustBeDecimal);
  323. decimal other = (decimal)value;
  324. return DecCalc.VarDecCmp(in this, in other);
  325. }
  326. public int CompareTo(decimal value)
  327. {
  328. return DecCalc.VarDecCmp(in this, in value);
  329. }
  330. // Divides two Decimal values.
  331. //
  332. public static decimal Divide(decimal d1, decimal d2)
  333. {
  334. DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2));
  335. return d1;
  336. }
  337. // Checks if this Decimal is equal to a given object. Returns true
  338. // if the given object is a boxed Decimal and its value is equal to the
  339. // value of this Decimal. Returns false otherwise.
  340. //
  341. public override bool Equals(object? value) =>
  342. value is decimal other &&
  343. DecCalc.VarDecCmp(in this, in other) == 0;
  344. public bool Equals(decimal value) =>
  345. DecCalc.VarDecCmp(in this, in value) == 0;
  346. // Returns the hash code for this Decimal.
  347. //
  348. public override int GetHashCode() => DecCalc.GetHashCode(in this);
  349. // Compares two Decimal values for equality. Returns true if the two
  350. // Decimal values are equal, or false if they are not equal.
  351. //
  352. public static bool Equals(decimal d1, decimal d2)
  353. {
  354. return DecCalc.VarDecCmp(in d1, in d2) == 0;
  355. }
  356. // Rounds a Decimal to an integer value. The Decimal argument is rounded
  357. // towards negative infinity.
  358. //
  359. public static decimal Floor(decimal d)
  360. {
  361. int flags = d.flags;
  362. if ((flags & ScaleMask) != 0)
  363. DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToNegativeInfinity);
  364. return d;
  365. }
  366. // Converts this Decimal to a string. The resulting string consists of an
  367. // optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
  368. // optionally followed by a decimal point (".") and another sequence of
  369. // digits.
  370. //
  371. public override string ToString()
  372. {
  373. return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
  374. }
  375. public string ToString(string? format)
  376. {
  377. return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
  378. }
  379. public string ToString(IFormatProvider? provider)
  380. {
  381. return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
  382. }
  383. public string ToString(string? format, IFormatProvider? provider)
  384. {
  385. return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
  386. }
  387. public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
  388. {
  389. return Number.TryFormatDecimal(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
  390. }
  391. // Converts a string to a Decimal. The string must consist of an optional
  392. // minus sign ("-") followed by a sequence of digits ("0" - "9"). The
  393. // sequence of digits may optionally contain a single decimal point (".")
  394. // character. Leading and trailing whitespace characters are allowed.
  395. // Parse also allows a currency symbol, a trailing negative sign, and
  396. // parentheses in the number.
  397. //
  398. public static decimal Parse(string s)
  399. {
  400. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  401. return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
  402. }
  403. public static decimal Parse(string s, NumberStyles style)
  404. {
  405. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  406. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  407. return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo);
  408. }
  409. public static decimal Parse(string s, IFormatProvider? provider)
  410. {
  411. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  412. return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider));
  413. }
  414. public static decimal Parse(string s, NumberStyles style, IFormatProvider? provider)
  415. {
  416. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  417. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  418. return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
  419. }
  420. public static decimal Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Number, IFormatProvider? provider = null)
  421. {
  422. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  423. return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
  424. }
  425. public static bool TryParse(string? s, out decimal result)
  426. {
  427. if (s == null)
  428. {
  429. result = 0;
  430. return false;
  431. }
  432. return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
  433. }
  434. public static bool TryParse(ReadOnlySpan<char> s, out decimal result)
  435. {
  436. return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
  437. }
  438. public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out decimal result)
  439. {
  440. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  441. if (s == null)
  442. {
  443. result = 0;
  444. return false;
  445. }
  446. return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
  447. }
  448. public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out decimal result)
  449. {
  450. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  451. return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
  452. }
  453. // Returns a binary representation of a Decimal. The return value is an
  454. // integer array with four elements. Elements 0, 1, and 2 contain the low,
  455. // middle, and high 32 bits of the 96-bit integer part of the Decimal.
  456. // Element 3 contains the scale factor and sign of the Decimal: bits 0-15
  457. // (the lower word) are unused; bits 16-23 contain a value between 0 and
  458. // 28, indicating the power of 10 to divide the 96-bit integer part by to
  459. // produce the Decimal value; bits 24-30 are unused; and finally bit 31
  460. // indicates the sign of the Decimal value, 0 meaning positive and 1
  461. // meaning negative.
  462. //
  463. public static int[] GetBits(decimal d)
  464. {
  465. return new int[] { d.lo, d.mid, d.hi, d.flags };
  466. }
  467. internal static void GetBytes(in decimal d, byte[] buffer)
  468. {
  469. Debug.Assert(buffer != null && buffer.Length >= 16, "[GetBytes]buffer != null && buffer.Length >= 16");
  470. buffer[0] = (byte)d.lo;
  471. buffer[1] = (byte)(d.lo >> 8);
  472. buffer[2] = (byte)(d.lo >> 16);
  473. buffer[3] = (byte)(d.lo >> 24);
  474. buffer[4] = (byte)d.mid;
  475. buffer[5] = (byte)(d.mid >> 8);
  476. buffer[6] = (byte)(d.mid >> 16);
  477. buffer[7] = (byte)(d.mid >> 24);
  478. buffer[8] = (byte)d.hi;
  479. buffer[9] = (byte)(d.hi >> 8);
  480. buffer[10] = (byte)(d.hi >> 16);
  481. buffer[11] = (byte)(d.hi >> 24);
  482. buffer[12] = (byte)d.flags;
  483. buffer[13] = (byte)(d.flags >> 8);
  484. buffer[14] = (byte)(d.flags >> 16);
  485. buffer[15] = (byte)(d.flags >> 24);
  486. }
  487. internal static decimal ToDecimal(ReadOnlySpan<byte> span)
  488. {
  489. Debug.Assert(span.Length >= 16, "span.Length >= 16");
  490. int lo = BinaryPrimitives.ReadInt32LittleEndian(span);
  491. int mid = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(4));
  492. int hi = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(8));
  493. int flags = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(12));
  494. return new decimal(lo, mid, hi, flags);
  495. }
  496. // Returns the larger of two Decimal values.
  497. //
  498. internal static ref readonly decimal Max(in decimal d1, in decimal d2)
  499. {
  500. return ref DecCalc.VarDecCmp(in d1, in d2) >= 0 ? ref d1 : ref d2;
  501. }
  502. // Returns the smaller of two Decimal values.
  503. //
  504. internal static ref readonly decimal Min(in decimal d1, in decimal d2)
  505. {
  506. return ref DecCalc.VarDecCmp(in d1, in d2) < 0 ? ref d1 : ref d2;
  507. }
  508. public static decimal Remainder(decimal d1, decimal d2)
  509. {
  510. DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2));
  511. return d1;
  512. }
  513. // Multiplies two Decimal values.
  514. //
  515. public static decimal Multiply(decimal d1, decimal d2)
  516. {
  517. DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2));
  518. return d1;
  519. }
  520. // Returns the negated value of the given Decimal. If d is non-zero,
  521. // the result is -d. If d is zero, the result is zero.
  522. //
  523. public static decimal Negate(decimal d)
  524. {
  525. return new decimal(in d, d.flags ^ SignMask);
  526. }
  527. // Rounds a Decimal value to a given number of decimal places. The value
  528. // given by d is rounded to the number of decimal places given by
  529. // decimals. The decimals argument must be an integer between
  530. // 0 and 28 inclusive.
  531. //
  532. // By default a mid-point value is rounded to the nearest even number. If the mode is
  533. // passed in, it can also round away from zero.
  534. public static decimal Round(decimal d) => Round(ref d, 0, MidpointRounding.ToEven);
  535. public static decimal Round(decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven);
  536. public static decimal Round(decimal d, MidpointRounding mode) => Round(ref d, 0, mode);
  537. public static decimal Round(decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode);
  538. private static decimal Round(ref decimal d, int decimals, MidpointRounding mode)
  539. {
  540. if ((uint)decimals > 28)
  541. throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
  542. if ((uint)mode > (uint)MidpointRounding.ToPositiveInfinity)
  543. throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
  544. int scale = d.Scale - decimals;
  545. if (scale > 0)
  546. DecCalc.InternalRound(ref AsMutable(ref d), (uint)scale, mode);
  547. return d;
  548. }
  549. internal static int Sign(in decimal d) => (d.lo | d.mid | d.hi) == 0 ? 0 : (d.flags >> 31) | 1;
  550. // Subtracts two Decimal values.
  551. //
  552. public static decimal Subtract(decimal d1, decimal d2)
  553. {
  554. DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), true);
  555. return d1;
  556. }
  557. // Converts a Decimal to an unsigned byte. The Decimal value is rounded
  558. // towards zero to the nearest integer value, and the result of this
  559. // operation is returned as a byte.
  560. //
  561. public static byte ToByte(decimal value)
  562. {
  563. uint temp;
  564. try
  565. {
  566. temp = ToUInt32(value);
  567. }
  568. catch (OverflowException)
  569. {
  570. Number.ThrowOverflowException(TypeCode.Byte);
  571. throw;
  572. }
  573. if (temp != (byte)temp) Number.ThrowOverflowException(TypeCode.Byte);
  574. return (byte)temp;
  575. }
  576. // Converts a Decimal to a signed byte. The Decimal value is rounded
  577. // towards zero to the nearest integer value, and the result of this
  578. // operation is returned as a byte.
  579. //
  580. [CLSCompliant(false)]
  581. public static sbyte ToSByte(decimal value)
  582. {
  583. int temp;
  584. try
  585. {
  586. temp = ToInt32(value);
  587. }
  588. catch (OverflowException)
  589. {
  590. Number.ThrowOverflowException(TypeCode.SByte);
  591. throw;
  592. }
  593. if (temp != (sbyte)temp) Number.ThrowOverflowException(TypeCode.SByte);
  594. return (sbyte)temp;
  595. }
  596. // Converts a Decimal to a short. The Decimal value is
  597. // rounded towards zero to the nearest integer value, and the result of
  598. // this operation is returned as a short.
  599. //
  600. public static short ToInt16(decimal value)
  601. {
  602. int temp;
  603. try
  604. {
  605. temp = ToInt32(value);
  606. }
  607. catch (OverflowException)
  608. {
  609. Number.ThrowOverflowException(TypeCode.Int16);
  610. throw;
  611. }
  612. if (temp != (short)temp) Number.ThrowOverflowException(TypeCode.Int16);
  613. return (short)temp;
  614. }
  615. // Converts a Decimal to a double. Since a double has fewer significant
  616. // digits than a Decimal, this operation may produce round-off errors.
  617. //
  618. public static double ToDouble(decimal d)
  619. {
  620. return DecCalc.VarR8FromDec(in d);
  621. }
  622. // Converts a Decimal to an integer. The Decimal value is rounded towards
  623. // zero to the nearest integer value, and the result of this operation is
  624. // returned as an integer.
  625. //
  626. public static int ToInt32(decimal d)
  627. {
  628. Truncate(ref d);
  629. if ((d.hi | d.mid) == 0)
  630. {
  631. int i = d.lo;
  632. if (!d.IsNegative)
  633. {
  634. if (i >= 0) return i;
  635. }
  636. else
  637. {
  638. i = -i;
  639. if (i <= 0) return i;
  640. }
  641. }
  642. throw new OverflowException(SR.Overflow_Int32);
  643. }
  644. // Converts a Decimal to a long. The Decimal value is rounded towards zero
  645. // to the nearest integer value, and the result of this operation is
  646. // returned as a long.
  647. //
  648. public static long ToInt64(decimal d)
  649. {
  650. Truncate(ref d);
  651. if (d.hi == 0)
  652. {
  653. long l = (long)d.Low64;
  654. if (!d.IsNegative)
  655. {
  656. if (l >= 0) return l;
  657. }
  658. else
  659. {
  660. l = -l;
  661. if (l <= 0) return l;
  662. }
  663. }
  664. throw new OverflowException(SR.Overflow_Int64);
  665. }
  666. // Converts a Decimal to an ushort. The Decimal
  667. // value is rounded towards zero to the nearest integer value, and the
  668. // result of this operation is returned as an ushort.
  669. //
  670. [CLSCompliant(false)]
  671. public static ushort ToUInt16(decimal value)
  672. {
  673. uint temp;
  674. try
  675. {
  676. temp = ToUInt32(value);
  677. }
  678. catch (OverflowException)
  679. {
  680. Number.ThrowOverflowException(TypeCode.UInt16);
  681. throw;
  682. }
  683. if (temp != (ushort)temp) Number.ThrowOverflowException(TypeCode.UInt16);
  684. return (ushort)temp;
  685. }
  686. // Converts a Decimal to an unsigned integer. The Decimal
  687. // value is rounded towards zero to the nearest integer value, and the
  688. // result of this operation is returned as an unsigned integer.
  689. //
  690. [CLSCompliant(false)]
  691. public static uint ToUInt32(decimal d)
  692. {
  693. Truncate(ref d);
  694. if ((d.hi | d.mid) == 0)
  695. {
  696. uint i = d.Low;
  697. if (!d.IsNegative || i == 0)
  698. return i;
  699. }
  700. throw new OverflowException(SR.Overflow_UInt32);
  701. }
  702. // Converts a Decimal to an unsigned long. The Decimal
  703. // value is rounded towards zero to the nearest integer value, and the
  704. // result of this operation is returned as a long.
  705. //
  706. [CLSCompliant(false)]
  707. public static ulong ToUInt64(decimal d)
  708. {
  709. Truncate(ref d);
  710. if (d.hi == 0)
  711. {
  712. ulong l = d.Low64;
  713. if (!d.IsNegative || l == 0)
  714. return l;
  715. }
  716. throw new OverflowException(SR.Overflow_UInt64);
  717. }
  718. // Converts a Decimal to a float. Since a float has fewer significant
  719. // digits than a Decimal, this operation may produce round-off errors.
  720. //
  721. public static float ToSingle(decimal d)
  722. {
  723. return DecCalc.VarR4FromDec(in d);
  724. }
  725. // Truncates a Decimal to an integer value. The Decimal argument is rounded
  726. // towards zero to the nearest integer value, corresponding to removing all
  727. // digits after the decimal point.
  728. //
  729. public static decimal Truncate(decimal d)
  730. {
  731. Truncate(ref d);
  732. return d;
  733. }
  734. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  735. private static void Truncate(ref decimal d)
  736. {
  737. int flags = d.flags;
  738. if ((flags & ScaleMask) != 0)
  739. DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> ScaleShift), MidpointRounding.ToZero);
  740. }
  741. public static implicit operator decimal(byte value) => new decimal((uint)value);
  742. [CLSCompliant(false)]
  743. public static implicit operator decimal(sbyte value) => new decimal(value);
  744. public static implicit operator decimal(short value) => new decimal(value);
  745. [CLSCompliant(false)]
  746. public static implicit operator decimal(ushort value) => new decimal((uint)value);
  747. public static implicit operator decimal(char value) => new decimal((uint)value);
  748. public static implicit operator decimal(int value) => new decimal(value);
  749. [CLSCompliant(false)]
  750. public static implicit operator decimal(uint value) => new decimal(value);
  751. public static implicit operator decimal(long value) => new decimal(value);
  752. [CLSCompliant(false)]
  753. public static implicit operator decimal(ulong value) => new decimal(value);
  754. public static explicit operator decimal(float value) => new decimal(value);
  755. public static explicit operator decimal(double value) => new decimal(value);
  756. public static explicit operator byte(decimal value) => ToByte(value);
  757. [CLSCompliant(false)]
  758. public static explicit operator sbyte(decimal value) => ToSByte(value);
  759. public static explicit operator char(decimal value)
  760. {
  761. ushort temp;
  762. try
  763. {
  764. temp = ToUInt16(value);
  765. }
  766. catch (OverflowException e)
  767. {
  768. throw new OverflowException(SR.Overflow_Char, e);
  769. }
  770. return (char)temp;
  771. }
  772. public static explicit operator short(decimal value) => ToInt16(value);
  773. [CLSCompliant(false)]
  774. public static explicit operator ushort(decimal value) => ToUInt16(value);
  775. public static explicit operator int(decimal value) => ToInt32(value);
  776. [CLSCompliant(false)]
  777. public static explicit operator uint(decimal value) => ToUInt32(value);
  778. public static explicit operator long(decimal value) => ToInt64(value);
  779. [CLSCompliant(false)]
  780. public static explicit operator ulong(decimal value) => ToUInt64(value);
  781. public static explicit operator float(decimal value) => ToSingle(value);
  782. public static explicit operator double(decimal value) => ToDouble(value);
  783. public static decimal operator +(decimal d) => d;
  784. public static decimal operator -(decimal d) => new decimal(in d, d.flags ^ SignMask);
  785. public static decimal operator ++(decimal d) => Add(d, One);
  786. public static decimal operator --(decimal d) => Subtract(d, One);
  787. public static decimal operator +(decimal d1, decimal d2)
  788. {
  789. DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), false);
  790. return d1;
  791. }
  792. public static decimal operator -(decimal d1, decimal d2)
  793. {
  794. DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), true);
  795. return d1;
  796. }
  797. public static decimal operator *(decimal d1, decimal d2)
  798. {
  799. DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2));
  800. return d1;
  801. }
  802. public static decimal operator /(decimal d1, decimal d2)
  803. {
  804. DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2));
  805. return d1;
  806. }
  807. public static decimal operator %(decimal d1, decimal d2)
  808. {
  809. DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2));
  810. return d1;
  811. }
  812. public static bool operator ==(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) == 0;
  813. public static bool operator !=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) != 0;
  814. public static bool operator <(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) < 0;
  815. public static bool operator <=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) <= 0;
  816. public static bool operator >(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) > 0;
  817. public static bool operator >=(decimal d1, decimal d2) => DecCalc.VarDecCmp(in d1, in d2) >= 0;
  818. //
  819. // IConvertible implementation
  820. //
  821. public TypeCode GetTypeCode()
  822. {
  823. return TypeCode.Decimal;
  824. }
  825. bool IConvertible.ToBoolean(IFormatProvider? provider)
  826. {
  827. return Convert.ToBoolean(this);
  828. }
  829. char IConvertible.ToChar(IFormatProvider? provider)
  830. {
  831. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
  832. }
  833. sbyte IConvertible.ToSByte(IFormatProvider? provider)
  834. {
  835. return Convert.ToSByte(this);
  836. }
  837. byte IConvertible.ToByte(IFormatProvider? provider)
  838. {
  839. return Convert.ToByte(this);
  840. }
  841. short IConvertible.ToInt16(IFormatProvider? provider)
  842. {
  843. return Convert.ToInt16(this);
  844. }
  845. ushort IConvertible.ToUInt16(IFormatProvider? provider)
  846. {
  847. return Convert.ToUInt16(this);
  848. }
  849. int IConvertible.ToInt32(IFormatProvider? provider)
  850. {
  851. return Convert.ToInt32(this);
  852. }
  853. uint IConvertible.ToUInt32(IFormatProvider? provider)
  854. {
  855. return Convert.ToUInt32(this);
  856. }
  857. long IConvertible.ToInt64(IFormatProvider? provider)
  858. {
  859. return Convert.ToInt64(this);
  860. }
  861. ulong IConvertible.ToUInt64(IFormatProvider? provider)
  862. {
  863. return Convert.ToUInt64(this);
  864. }
  865. float IConvertible.ToSingle(IFormatProvider? provider)
  866. {
  867. return Convert.ToSingle(this);
  868. }
  869. double IConvertible.ToDouble(IFormatProvider? provider)
  870. {
  871. return Convert.ToDouble(this);
  872. }
  873. decimal IConvertible.ToDecimal(IFormatProvider? provider)
  874. {
  875. return this;
  876. }
  877. DateTime IConvertible.ToDateTime(IFormatProvider? provider)
  878. {
  879. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
  880. }
  881. object IConvertible.ToType(Type type, IFormatProvider? provider)
  882. {
  883. return Convert.DefaultToType((IConvertible)this, type, provider);
  884. }
  885. }
  886. }