-
Notifications
You must be signed in to change notification settings - Fork 57
/
Velthuis.BigDecimals.pas
2521 lines (2135 loc) · 96 KB
/
Velthuis.BigDecimals.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{---------------------------------------------------------------------------}
{ }
{ File: Velthuis.BigDecimals.pas }
{ HFunction: A multiple precision decimal implementation, based on the }
{ BigInteger implementation in Velthuis.BigIntegers.pas. }
{ Language: Delphi version XE2 or later }
{ Author: Rudy Velthuis }
{ Copyright: (c) 2016,2017 Rudy Velthuis }
{ ------------------------------------------------------------------------- }
{ }
{ License: Redistribution and use in source and binary forms, with or }
{ without modification, are permitted provided that the }
{ following conditions are met: }
{ }
{ * Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the following }
{ disclaimer. }
{ * Redistributions in binary form must reproduce the above }
{ copyright notice, this list of conditions and the following }
{ disclaimer in the documentation and/or other materials }
{ provided with the distribution. }
{ }
{ Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" }
{ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT }
{ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND }
{ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO }
{ EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE }
{ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, }
{ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, }
{ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, }
{ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED }
{ AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT }
{ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) }
{ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF }
{ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. }
{ }
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{ }
{ Notes: The interface of BigDecimal is mainly the same as the Java }
{ BigDecimal type. But because Java does not have operator }
{ overloading, it uses methods for all the arithmetic }
{ operations, so it is not a big problem to give these extra }
{ MathContext parameters, e.g for division or conversions. }
{ Division might result in a non-terminating expansion (e.g. }
{ 1 / 3 does not terminate, so there must be a given limit on }
{ the number of digits. This generally requires rounding). }
{ }
{ To be able to use overloaded operators, I decided to give }
{ the class DefaultPrecision and DefaultRoundingMode }
{ properties, to be used in any division or conversion that }
{ requires these. Additionally, there are methods that take }
{ Precision or RoundingMode parameters, which do not use the }
{ defaults. }
{ }
{ The names of some of the methods and identifiers were chosen }
{ to be more in line with BigInteger and with other Delphi }
{ functions and constants. }
{ }
{ The ToString and ToPlainString methods do follow the Java }
{ interface, i.e. ToString produces scientific notation where }
{ this makes sense while ToPlainString produces plain notation, }
{ even if this means that the string can get very long and }
{ contains many zeroes. Both ToString and ToPlainString do not }
{ use local format settings, but use the system invariant }
{ format settings instead. This allows the output of these }
{ methods to be used as valid input for Parse and TryParse (so }
{ called roundtrip conversion). }
{ If you want output based on FormatSettings, use my upcoming }
{ NumberFormatter instead. }
{ }
{ Based on the Java examples and on my Decimal types, I use a }
{ Scale which is positive for fractions, even if a positive }
{ exponent might make more sense. }
{ }
{ BigDecimals are immutable. This means that if a method }
{ returns a value that differs from the value of the current }
{ BigDecimal, a new BigDecimal is returned. }
{ }
{---------------------------------------------------------------------------}
unit Velthuis.BigDecimals;
(* TODO: BigDecimals are ssslllooowww. This piece of code, with CIterations = 5*1000*1000,
SetLength(arr, CIterations);
pi := '3.14159';
for I := 0 to High(arr) do
arr[I] := BigDecimal(I);
for I := 0 to High(arr) do
arr[I] := arr[I] * pi / (pi * BigDecimal(I) + BigDecimal.One);
is 500 times(!) slower than the Double equivalent. That is extremely slow.
Note that simplyfying this to do BigDecimal(I) * pi only once will only take away 1% of that.
It is crucial to find out what makes this code so terribly slow.
Note: probably BigInteger.DivMod is the slow part.
Note: It might make sense to use a NativeInt to hold the FValue of small BigDecimals, instead
of always BigIntegers.
It might also make sense to make BigInteger.DivMod a lot faster for small values.
*)
interface
uses
CompilerAndRTLVersions,
System.SysUtils,
System.Math,
Velthuis.BigIntegers;
{$IF CompilerVersion >= CompilerVersionDelphi2010} // Delphi 2010
{$DEFINE HasClassConstructors}
{$IFEND}
{$IF CompilerVersion >= CompilerVersionDelphiXE}
{$CODEALIGN 16}
{$ALIGN 16}
{$IFEND}
{$IF CompilerVersion >= CompilerVersionDelphiXE3}
{$LEGACYIFEND ON}
{$IFEND}
{$IF CompilerVersion < CompilerVersionDelphiXE8}
{$IF (DEFINED(WIN32) or DEFINED(CPUX86)) AND NOT DEFINED(CPU32BITS)}
{$DEFINE CPU32BITS}
{$IFEND}
{$IF (DEFINED(WIN64) OR DEFINED(CPUX64)) AND NOT DEFINED(CPU64BITS)}
{$DEFINE CPU64BITS}
{$IFEND}
{$IFEND}
{$IF SizeOf(Extended) > SizeOf(Double)}
{$DEFINE HasExtended}
{$IFEND}
{$DEFINE EXPERIMENTAL}
type
// Note: where possible, existing exception types are used, e.g. EConvertError, EOverflow, EUnderflow,
// EZeroDivide from System.SysUtils, etc.
/// <summary>This exception is raised when on rounding, rmUnnecessary is specified, indicating that we
/// "know" that rounding is not necessary, and the code determines that, to get the desired result, rounding is
/// necessary after all.</summary>
ERoundingNecessary = class(Exception);
EIntPowerExponent = class(Exception);
PBigDecimal = ^BigDecimal;
/// <summary>BigDecimal is a multiple precision floating decimal point binary significand data type. It consists
/// of a BigInteger and a scale, which is the negative decimal exponent.</summary>
/// <remarks><para>BigDecimal "remembers" the precision with which it was initialized. So BigDecimal('1.79') and
/// BigDecimal('1.790000') are distinct values, although they compare as equal.</para>
/// <para>BigDecimals are immutable. This means that any function or operator that returns a different
/// value returns a new BigDecimal.</para></remarks>
BigDecimal = record
public
/// <summary>RoundingMode governs which rounding mode is used for certain operations, like division or
/// conversion.</summary>
/// <param name="rmUp">Rounds away from zero</param>
/// <param name="rmDown">Rounds towards zero</param>
/// <param name="rmCeiling">Rounds towards +infinity</param>
/// <param name="rmFloor">Rounds towards -infinity</param>
/// <param name="rmNearestUp">Rounds to nearest higher order digit and, on tie, away from zero</param>
/// <param name="rmNearestDown">Rounds to nearest higher order digit and, on tie, towards zero</param>
/// <param name="rmNearestEven">Rounds to nearest higher order digit and, on tie, to nearest even digit</param>
/// <param name="rmUnnecessary">Assumes an exact result, and raises an exception if rounding is necessary</param>
type
RoundingMode =
(
rmUp, // Round away from zero
rmDown, // Round towards zero
rmCeiling, // Round towards +infinity
rmFloor, // Round towards -infinity
rmNearestUp, // Round .5 away from 0
rmNearestDown, // Round .5 towards 0
rmNearestEven, // Round .5 towards the nearest even value
rmUnnecessary // Do not round, because operation has exact result
);
const
/// <summary>Maximum value a BigDecimal's scale can have</summary>
MaxScale = MaxInt div SizeOf(Velthuis.BigIntegers.TLimb);
/// <summary>Minimum value a BigDecimal's scale can have</summary>
MinScale = -MaxScale - 1;
{$IF defined(CPU32BITS)}
IntPowerExponentThreshold = 128;
{$ELSE}
IntPowerExponentThreshold = 256;
{$IFEND}
private
type
// Error codes to be used when calling the private static BigDecimal.Error method.
TErrorCode = (ecParse, ecDivByZero, ecConversion, ecOverflow, ecUnderflow, ecInvalidArg, ecRounding, ecExponent);
var
// The unscaled value of the BigDecimal.
FValue: BigInteger;
// The scale which is the power of ten by which the UnscaledValue must be divided to get the BigDecimal value.
// So 1.79 is coded as FValue = 179 and FScale = 2, whereas 1.7900 is coded as FValue = 17900 and FScale = 4.
FScale: Int32;
// The precision is the number of digits in FValue. This is originally 0, and calculated when used the first time.
// If this value is not 0, then the precision does not need to be calculated and this value can be used.
FPrecision: Int32;
class var
// Default rounding mode. See above.
FDefaultRoundingMode: RoundingMode;
// Default precision (number of significant digits) used for e.g. division.
FDefaultPrecision: Integer;
// Set this to False if trailing zeroes should not be reduced to the preferred scale after a division.
FReduceTrailingZeros: Boolean;
// Default character used to indicate exponent in scientific notation output. Either 'E' or 'e'. Default 'e'.
FExponentDelimiter: Char;
// BigDecimal with value -1: unscaled value = -1, scale = 0.
FMinusOne: BigDecimal;
// BigDecimal with value 0: unscaled value = 0, scale = 0.
FZero: BigDecimal;
// BigDecimal with value 1: unscaled value = 1, scale = 0.
FOne: BigDecimal;
// BigDecimal with Value 2: unscaled value = 2, scale = 0.
FTwo: BigDecimal;
// BigDecimal with value 10: unscaled value = 10, scale = 0.
FTen: BigDecimal;
// BigDecimal with value 0.5: unscaled value = 5, scale = 1.
FHalf: BigDecimal;
// BigDecimal with value 0.1: unscaled value = 1, scale = 1.
FOneTenth: BigDecimal;
{$IFDEF HasClassConstructors}
class constructor InitClass;
{$ELSE}
class procedure InitClass; static;
{$ENDIF}
// Increments Quotient if its current value, the value of the remainder and the given rounding mode and sign require it.
class procedure AdjustForRoundingMode(var Quotient: BigInteger; const Divisor, Remainder: BigInteger; Sign: Integer; Mode: RoundingMode); static;
// Divides FValue by a power of ten to remove as many trailing zeros possible without altering its value,
// i.e. it leaves other digits intact, and adjusts the scale accordingly.
// Say we have 1.7932400000000 as value, i.e. [FValue=17932400000000, FScale=13], and the target scale
// is 2, then the result is [179324, 5], which is as close to scale=2 as we can get without altering the value.
class procedure InPlaceRemoveTrailingZeros(var Value: BigDecimal; TargetScale: Integer); static;
// Converts the current BigDecimal to sign, significand and exponent for the given significand size in bits.
// Can be used to convert to components for Single, Double and Extended.
class procedure ConvertToFloatComponents(const Value: BigDecimal; SignificandSize: Integer;
var Sign: Integer; var Exponent: Integer; var Significand: UInt64); static;
// Converts the current sign, significand and exponent, extracted from a Single, Double or Extended,
// into a BigDecimal.
class procedure ConvertFromFloatComponents(Sign: TValueSign; Exponent: Integer; Significand: UInt64;
var Result: BigDecimal); static;
// Raises exceptions where the type depends on the error code and the message on the arguments.
class procedure Error(ErrorCode: TErrorCode; ErrorInfo: array of const); static;
// Gets a BigInteger of the given power of five, either from a prefilled array or using BigInteger.Pow.
class function GetPowerOfFive(N: Integer): BigInteger; static;
// Gets a BigInteger of the given power of ten, either from a prefilled array or using BigInteger.Pow.
class function GetPowerOfTen(N: Integer): BigInteger; static;
// Initialize or reset scale and precision to 0.
procedure Init; inline;
// Checks if the NewScale value is a valid scale value. If so, simply returns NewScale. Otherwise, raises
// an appropriate exception.
class function RangeCheckedScale(NewScale: Int32): Integer; static;
// Only allows 'e' or 'E' as exponent delimiter for scientific notation output.
class procedure SetExponentDelimiter(const Value: Char); static;
public
/// <summary>Creates a BigDecimal with given unscaled value and given scale.</summary>
constructor Create(const UnscaledValue: BigInteger; Scale: Integer); overload;
{$IFDEF HasExtended}
/// <summary>Creates a BigDecimal with the same value as the given Extended parameter.</summary>
/// <exception cref="EInvalidArgument">EInvalidArgument is raised if the parameter contains a NaN or infinity.</exception>
constructor Create(const E: Extended); overload;
{$ENDIF}
/// <summary>Creates a BigDecimal with the same value as the given Double parameter.</summary>
/// <exception cref="EInvalidArgument">EInvalidArgument is raised if the parameter contains a NaN or infinity.</exception>
constructor Create(const D: Double); overload;
/// <summary>Creates a BigDecimal with the same value as the given Single parameter.</summary>
/// <exception cref="EInvalidArgument">EInvalidArgument is raised if the parameter contains a NaN or infinity.</exception>
constructor Create(const S: Single); overload;
/// <summary>Creates a BigDecimal with the value that results from parsing the given string parameter.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the string cannot be parsed to a valid BigDecimal.</exception>
constructor Create(const S: string); overload;
/// <summary>Creates a BigDecimal with the same value as the given BigInteger parameter.</summary>
constructor Create(const UnscaledValue: BigInteger); overload;
/// <summary>Creates a BigDecimal with the same value as the given unsigned 64 bit integer parameter.</summary>
constructor Create(const U64: UInt64); overload;
/// <summary>Creates a BigDecimal with the same value as the given signed 64 bit integer parameter.</summary>
constructor Create(const I64: Int64); overload;
/// <summary>Creates a BigDecimal with the same value as the given unsigned 32 bit integer parameter.</summary>
constructor Create(U32: UInt32); overload;
/// <summary>Creates a BigDecimal with the same value as the given signed 32 bit integer parameter.</summary>
constructor Create(I32: Int32); overload;
// -- Mathematical operators --
/// <summary>Adds two BigDecimals. The new scale is Max(Left.Scale, Right.Scale).</summary>
/// <param name="Left">The augend</param>
/// <param name="Right">The addend</param>
/// <returns><code>Result := Left + Right;</code></returns>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
class operator Add(const Left, Right: BigDecimal): BigDecimal;
/// <summary>Subtracts two BigDecimals. The new scale is Max(Left.Scale, Right.Scale).</summary>
/// <param name="Left">The minuend</param>
/// <param name="Right">The subtrahend</param>
/// <returns><code>Result := Left - Right;</code></returns>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
class operator Subtract(const Left, Right: BigDecimal): BigDecimal;
/// <summary>Multiplies two BigDecimals. The new scale is Left.Scale + Right.Scale.</summary>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
/// <exception cref="EUnderflow">EUnderflow is raised if the result would become too small.</exception>
class operator Multiply(const Left, Right: BigDecimal): BigDecimal;
/// <summary><para>Divides two BigDecimals.</para>
/// <para>Uses the default precision and rounding mode to obtain the result.</para>
/// <para>The target scale is <c>Left.Scale - Right.Scale</c>. The result will approach this target scale as
/// much as possible by removing any excessive trailing zeros.</para></summary>
/// <param name="Left">The dividend (enumerator)</param>
/// <param name="Right">The divisor (denominator)</param>
/// <returns><code>Result := Left / Right;</code></returns>
/// <exception cref="EZeroDivide">EZeroDivide is raised if the divisor is zero.</exception>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
/// <exception cref="EUnderflow">EUnderflow is raised if the result would become too small.</exception>
class operator Divide(const Left, Right: BigDecimal): BigDecimal;
/// <summary>Divides two BigDecimals to obtain an integral result.</summary>
/// <param name="left">The dividend</param>
/// <param name="Right">The divisor</param>
/// <returns><code>Result := Left div Right;</code></returns>
/// <exception cref="EZeroDivide">EZeroDivide is raised if the divisor is zero.</exception>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
/// <exception cref="EUnderflow">EUnderflow is raised if the result would become too small.</exception>
class operator IntDivide(const Left, Right: BigDecimal): BigDecimal;
/// <summary>Returns the remainder after Left is divided by right to an integral value.</summary>
/// <param name="Left">The dividend</param>
/// <param name="Right">The divisor</param>
/// <returns><code>Result := Left - Right * (Left div Right);</code></returns>
/// <exception cref="EZeroDivide">EZeroDivide is raised if the divisor is zero.</exception>
/// <exception cref="EOverflow">EOverflow is raised if the result would become too big.</exception>
/// <exception cref="EUnderflow">EUnderflow is raised if the result would become too small.</exception>
class operator Modulus(const Left, Right: BigDecimal): BigDecimal;
/// <summary>Negates the given BigDecimal.</summary>
/// <returns><code>Result := -Value;</code></returns>
class operator Negative(const Value: BigDecimal): BigDecimal;
/// <summary>Called when a BigDecimal is preceded by a unary +. Currently a no-op.</summary>
/// <returns><code>Result := +Value;</code></returns>
class operator Positive(const Value: BigDecimal): BigDecimal;
/// <summary>Rounds the given BigDecimal to an Int64.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the result is too large to fit in an Int64.</exception>
class operator Round(const Value: BigDecimal): Int64;
/// <summary>Truncates (ronds down towards 0) the given BigDecimal to an Int64.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the result is too large to fit in an Int64.</exception>
class operator Trunc(const Value: BigDecimal): Int64;
// -- Comparison operators --
/// <summary>Returns True if Left is mathematically less than or equal to Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left <= Right;</code></returns>
class operator LessThanOrEqual(const Left, Right: BigDecimal): Boolean;
/// <summary>Returns True if Left is mathematically less than Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left < Right;</code></returns>
class operator LessThan(const left, Right: BigDecimal): Boolean;
/// <summary>Returns True if Left is mathematically greater than or equal to Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left >= Right;</code></returns>
class operator GreaterThanOrEqual(const Left, Right: BigDecimal): Boolean;
/// <summary>Returns True if Left is mathematically greater than Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left > Right;</code></returns>
class operator GreaterThan(const Left, Right: BigDecimal): Boolean;
/// <summary>Returns True if Left is mathematically equal to Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left = Right;</code></returns>
class operator Equal(const left, Right: BigDecimal): Boolean;
/// <summary>Returns True if Left is mathematically not equal to Right.</summary>
/// <param name="Left">The first operand</param>
/// <param name="Right">The second operand</param>
/// <returns><code>Result := Left <> Right;</code></returns>
class operator NotEqual(const Left, Right: BigDecimal): Boolean;
// -- Implicit conversion operators --
{$IFDEF HasExtended}
/// <summary>Returns a BigDecimal with the exact value of the given Extended parameter.</summary>
class operator Implicit(const E: Extended): BigDecimal;
{$ENDIF}
/// <summary>Returns a BigDecimal with the exact value of the given Double parameter.</summary>
class operator Implicit(const D: Double): BigDecimal;
/// <summary>Returns a BigDecimal with the exact value of the given Single parameter.</summary>
class operator Implicit(const S: Single): BigDecimal;
/// <summary>Returns a BigDecimal with the value parsed from the given string parameter.</summary>
class operator Implicit(const S: string): BigDecimal;
/// <summary>Returns a BigDecimal with the value of the given BigInteger parameter.</summary>
class operator Implicit(const UnscaledValue: BigInteger): BigDecimal;
/// <summary>Returns a BigDecimal with the value of the given unsigned 64 bit integer parameter.</summary>
class operator Implicit(const U: UInt64): BigDecimal;
/// <summary>Returns a BigDecimal with the value of the given signed 64 bit integer parameter.</summary>
class operator Implicit(const I: Int64): BigDecimal;
/// <summary>Returns a BigDecimal with the value of the given unsigned 64 bit integer parameter.</summary>
class operator Implicit(const U: UInt32): BigDecimal;
/// <summary>Returns a BigDecimal with the value of the given signed 64 bit integer parameter.</summary>
class operator Implicit(const I: Int32): BigDecimal;
// -- Explicit conversion operators --
{$IFDEF HasExtended}
/// <summary>Returns an Extended with the best approximation of the given BigDecimal value.
/// The conversion uses the default rounding mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
class operator Explicit(const Value: BigDecimal): Extended;
{$ENDIF}
/// <summary>Returns a Double with the best approximation of the given BigDecimal value.
/// The conversion uses the default rounding mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
class operator Explicit(const Value: BigDecimal): Double;
/// <summary>Returns a Single with the best approximation of the given BigDecimal value.
/// The conversion uses the default rounding mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
class operator Explicit(const Value: BigDecimal): Single;
/// <summary>Returns a string representation of the given BigDecimal value.</summary>
class operator Explicit(const Value: BigDecimal): string;
/// <summary>Returns a BigInteger with the rounded value of the given BigDecimal value.
/// The conversion uses the rounding mode rmDown, i.e. it truncates.</summary>
class operator Explicit(const Value: BigDecimal): BigInteger;
/// <summary>Returns an unsigned 64 bit integer with the rounded value of the given BigDecimal value.
/// The conversion uses the default rounding mode rmDown, i.e. it truncates.</summary>
/// <remarks><para>If the value of the rounded down BigDecimal does not fit in an UInt64, only the low
/// 64 bits of that value are used to form the result.</para>
/// <para>This is analogue to</para>
/// <code> myByte := Byte(MyUInt64);</code>
/// <para>Only the low 8 bits of myUInt64 are copied to the byte.</para></remarks>
class operator Explicit(const Value: BigDecimal): UInt64;
/// <summary>Returns a signed 64 bit integer with the rounded value of the given BigDecimal value.
/// The conversion uses the default rounding mode rmDown, i.e. it truncates.</summary>
/// <remarks><para>If the value of the rounded down BigDecimal does not fit in an Int64, only the low
/// 64 bits of that value are used to form the result.</para>
/// <para>This is analogue to</para>
/// <code> myByte := Byte(MyUInt64);</code>
/// <para>Only the low 8 bits of myUInt64 are copied to the byte.</para></remarks>
class operator Explicit(const Value: BigDecimal): Int64;
/// <summary>Returns an unsigned 32 bit integer with the rounded value of the given BigDecimal value.
/// The conversion uses the default rounding mode rmDown, i.e. it truncates.</summary>
/// <remarks><para>If the value of the rounded down BigDecimal does not fit in an UInt32, only the low
/// 32 bits of that value are used to form the result.</para>
/// <para>This is analogue to</para>
/// <code> myByte := Byte(MyUInt32);</code>
/// <para>Only the low 8 bits of myUInt32 are copied to the byte.</para></remarks>
class operator Explicit(const Value: BigDecimal): UInt32;
/// <summary>Returns a signed 32 bit integer with the rounded value of the given BigDecimal value.
/// The conversion uses the default rounding mode rmDown, i.e. it truncates.</summary>
/// <remarks><para>If the value of the rounded down BigDecimal does not fit in an Int32, only the low
/// 32 bits of that value are used to form the result.</para>
/// <para>This is analogue to</para>
/// <code> myByte := Byte(MyUInt32);</code>
/// <para>Only the low 8 bits of myUInt32 are copied to the byte.</para></remarks>
class operator Explicit(const Value: BigDecimal): Int32;
// -- Conversion functions --
{$IFDEF HasExtended}
function AsExtended: Extended;
{$ENDIF}
function AsDouble: Double;
function AsSingle: Single;
function AsBigInteger: BigInteger;
function AsUInt64: UInt64;
function AsInt64: Int64;
function AsUInt32: UInt32;
function AsInt32: Int32;
// -- Mathematical functions --
/// <summary>Returns the sum of the given parameters. The new scale is Max(Left.Scale, Right.Scale).</summary>
class function Add(const Left, Right: BigDecimal): BigDecimal; overload; static;
/// <summary>Returns the difference of the given parameters. The new scale is Max(Left.Scale, Right.Scale).</summary>
class function Subtract(const Left, Right: BigDecimal): BigDecimal; overload; static;
/// <summary>Returns the product ofthe given parameters. The new scale is Left.Scale + Right.Scale.</summary>
class function Multiply(const Left, Right: BigDecimal): BigDecimal; overload; static;
/// <summary><para>Returns the quotient of the given parameters. Left is the dividend, Right the divisor.</para>
/// <para>Raises an exception if the value of Right is equal to 0.</para>
/// <para>Uses the default rounding mode and precision.
/// Raises an exception if the rounding mode is rmUnnecessary, but rounding turns out to be necessary.</para>
/// <para>The preferred new scale is Left.Scale - Right.Scale. Removes any trailing zero digits to
/// approach that preferred scale without altering the significant digits.</para></summary>
class function Divide(const Left, Right: BigDecimal): BigDecimal; overload; static;
/// <summary><para>Returns the quotient of the given parameters. Left is the dividend, Right the divisor.</para>
/// <para>Raises an exception if the value of Right is equal to 0.</para>
/// <para>Uses the given rounding mode and precision.
/// Raises an exception if the rounding mode is rmUnnecessary, but rounding turns out to be necessary.</para>
/// <para>The preferred new scale is Left.Scale - Right.Scale. Removes any trailing zero digits to
/// approach that preferred scale without altering the significant digits.</para></summary>
class function Divide(const Left, Right: BigDecimal; Precision: Integer; ARoundingMode: RoundingMode): BigDecimal; overload; static;
/// <summary><para>Returns the quotient of the given parameters. Left is the dividend, Right the divisor.</para>
/// <para>Raises an exception if the value of Right is equal to 0.</para>
/// <para>Uses the given rounding mode and the default precision.
/// Raises an exception if the rounding mode is rmUnnecessary, but rounding turns out to be necessary.</para>
/// <para>The preferred new scale is Left.Scale - Right.Scale. Removes any trailing zero digits to
/// approach that preferred scale without altering the significant digits.</para></summary>
class function Divide(const Left, Right: BigDecimal; Precision: Integer): BigDecimal; overload; static;
/// <summary><para>Returns the quotient of the given parameters. Left is the dividend, Right the divisor.</para>
/// <para>Raises an exception if the value of Right is equal to 0.</para>
/// <para>Uses the default rounding mode and the given precision.
/// Raises an exception if the rounding mode is rmUnnecessary, but rounding turns out to be necessary.</para>
/// <para>The preferred new scale is Left.Scale - Right.Scale. Removes any trailing zero digits to
/// approach that preferred scale without altering the significant digits.</para></summary>
class function Divide(const Left, Right: BigDecimal; ARoundingMode: RoundingMode): BigDecimal; overload; static;
/// <summary>Returns the negated value of the given BigDecimal parameter.</summary>
class function Negate(const Value: BigDecimal): BigDecimal; overload; static;
/// <summary>Rounds the value of the given BigDecimal parameter to a signed 64 bit integer. Uses the default
/// rounding mode for the conversion.</summary>
class function Round(const Value: BigDecimal): Int64; overload; static;
/// <summary>Rounds the value of the given BigDecimal parameter to a signed 64 bit integer. Uses the default
/// rounding mode for the conversion.</summary>
class function Round(const Value: BigDecimal; ARoundingMode: RoundingMode): Int64; overload; static;
/// <summary><para>Returns the BigDecimal remainder after the division of the two parameters.</para>
/// <para>Uses the default precision and rounding mode for the division.</para></summary>
/// <returns><para>The result has the value of</para>
/// <code> Left - (Left / Right).Int * Right</code></returns>
class function Remainder(const Left, Right: BigDecimal): BigDecimal; static;
/// <summary>Returns the absolute (non-negative) value of the given BigDecimal.</summary>
class function Abs(const Value: BigDecimal): BigDecimal; overload; static;
/// <summary>Returns the square of the given BigDecimal.<summary>
class function Sqr(const Value: BigDecimal): BigDecimal; overload; static;
/// <summary>Returns the square root of the given BigDecimal, using the given precision.</summary>
class function Sqrt(const Value: BigDecimal; Precision: Integer): BigDecimal; overload; static;
/// <summary>Returns the square root of the given BigDecimal, using the default precision.</summary>
class function Sqrt(const Value: BigDecimal): BigDecimal; overload; static;
/// <summary>Returns the integer power of the given BigDecimal, in unlimited precision.</summary>
class function IntPower(const Base: BigDecimal; Exponent: Integer): BigDecimal; overload; static;
/// <summary>Returns the integer power of the given BigDecimal, in the given precision.</summary>
class function IntPower(const Base: BigDecimal; Exponent, Precision: Integer): BigDecimal; overload; static;
// -- Comparison functions --
/// <summary>Returns 1 if Left is matehamtically greater than Right, 0 if Left is mathematically equal to Right and
/// -1 is Left is matheamtically less than Right.</summary>
class function Compare(const Left, Right: BigDecimal): TValueSign; static;
/// <summary>Returns the maximum of the two given BigDecimal values.</summary>
class function Max(const Left, Right: BigDecimal): BigDecimal; static;
/// <summary>Returns the minimum of the two given BigDecimal values.</summary>
class function Min(const Left, Right: BigDecimal): BigDecimal; static;
// -- Parsing --
/// <summary>Tries to parse the given string as a BigDecimal into Res, using the given format settings.</summary>
/// <returns>Returns only True of the function was successful.</returns>
class function TryParse(const S: string; const Settings: TFormatSettings; out Value: BigDecimal): Boolean;
overload; static;
/// <summary>Tries to parse the given string as a BigDecimal into Res, using the system invariant format
/// settings.</summary>
/// <returns>Returns only True of the function was successful.</returns>
class function TryParse(const S: string; out Value: BigDecimal): Boolean;
overload; static;
/// <summary>Returns the BigDecimal with a value as parsed from the given string, using the given
/// format settings.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the string cannot be parsed to a valid BigDecimal.</exception>
class function Parse(const S: string; const Settings: TFormatSettings): BigDecimal; overload; static;
/// <summary>Returns the BigDecimal with a value as parsed from the given string, using the system
/// invariant format settings.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the string cannot be parsed to a valid BigDecimal.</exception>
class function Parse(const S: string): BigDecimal; overload; static;
// -- Instance methods --
/// <summary>Returns true if the current BigDecimal's value equals zero.</summary>
function IsZero: Boolean;
/// <summary>Returns true if the current BigDecimal's value is positive.</summary>
function IsPositive: Boolean;
/// <summary>Returns true if the current BigDecimal's value is negative.</summary>
function IsNegative: Boolean;
/// <summary>Returns the sign of the current BigDecimal: -1 if negative, 0 if zero, 1 if positive.</summary>
function Sign: TValueSign;
/// <summary>Returns the absolute (i.e. non-negative) value of the current BigDecimal.</summary>
function Abs: BigDecimal; overload;
/// <summary>Rounds the current BigDecimal to a value with at most Digits digits, using the given rounding
/// mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
/// <remarks><para>The System.Math.RoundTo function uses the floating point equivalent of rmNearestEven, while
/// System.Math.SimpleRoundTo uses the equivalent of rmNearestUp. This function is more versatile.</para>
/// <para>This is exactly equivalent to</para>
/// <code> RoundToScale(-Digits, ARoundingMode);</code></remarks>
function RoundTo(Digits: Integer; ARoundingMode: RoundingMode): BigDecimal; overload;
/// <summary>Rounds the current BigDecimal to a value with at most Digits digits, using the default rounding
/// mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
/// <remarks><para>The System.Math.RoundTo function uses the floating point equivalent of rmNearestEven, while
/// System.Math.SimpleRoundTo uses the equivalent of rmNearestUp. This function is more versatile.</para>
/// <para>This is exactly equivalent to</para>
/// <code> RoundToScale(-Digits, DefaultRoundingMode);</code></remarks>
function RoundTo(Digits: Integer): BigDecimal; overload;
/// <summary>Rounds the current BigDecimal to a value with the given scale, using the given rounding
/// mode.</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
function RoundToScale(NewScale: Integer; ARoundingMode: RoundingMode): BigDecimal;
/// <summary>Rounds the current Bigdecimal to a certain precision (number of significant digits).</summary>
/// <exception cref="ERoundingNecessary">ERoundingNecessary is raised if a rounding mode
/// rmUnnecessary was specified but rounding is necessary after all.</exception>
function RoundToPrecision(APrecision: Integer): BigDecimal; overload;
/// <summary>Returns a new BigDecimal with the decimal point shifted to the left by the given number of positions</summary>
function MovePointLeft(Digits: Integer): BigDecimal;
/// <summary>Returns a new BigDecimal with the decimal point shifted to the right by the given number of positions</summary>
function MovePointRight(Digits: Integer): BigDecimal;
/// <summary>Returns a value with any fraction (digits after the decimal point) removed from the current
/// BigDecimal.</summary>
/// <remarks>Example: BigDecimal('1234.5678') results in BigDecimal('1234').</remarks>.
function Int: BigDecimal;
/// <summary>Returns a signed 64 bit integer with any fraction (digits after the decimal point) removed
/// from the current BigDecimal.</summary>
/// <exception cref="EConvertError">EConvertError is raised if the result does not fit in an Int64.</exception>
function Trunc: Int64;
/// <summary>Returns a BigDecimal containing only the fractional part (digits after the decimal point) of
/// the current BigDecimal.</summary>
/// <remarks>Example: BigDecimal('1234.5678') results in BigDecimal('0.5678').</remarks>
function Frac: BigDecimal;
/// <summary>Returns a BigDecimal rounded down, towards negative infinity, to the next integral value.</summary>
/// <remarks>Example: BigDecimal('1234.5678') results in BigDecimal('1234');</remarks>
function Floor: BigDecimal;
/// <summary>Returns a BigDecimal rounded up, towards positive infinity, to the next integral value.</summary>
/// <remarks>Example: BigDecimal('1234.5678') results in BigDecimal('1235');</remarks>
function Ceil: BigDecimal;
/// <summary>Returns the number of significant digits of the current BigDecimal.</summary>
function Precision: Integer;
/// <summary>Returns the reciprocal of the current BigDecimal, using the given precision</summary>
/// <exception cref="EZeroDivide">EZeroDivide is raised if the current BigDecimal is zero.</exception>
function Reciprocal(Precision: Integer): BigDecimal; overload;
/// <summary>Returns the reciprocal of the current BigDecimal, using the given precision</summary>
function Reciprocal: BigDecimal; overload;
/// <summary>Returns a new BigDecimal with all trailing zeroes (up to the preferred scale) removed from the
/// current BigDecimal. No significant digits will be removed and the numerical value of the result compares
/// as equal to the original value.</summary>
/// <param name="TargetScale">The scale up to which trailing zeroes can be removed. It is possible that
/// fewer zeroes are removed, but never more than necessary to reach the preferred scale.</param>
/// <remarks><para>Note that no rounding is required. Removal stops at the rightmost non-zero digit.</para>
/// <para>Example: BigDecimal('1234.5678900000').RemoveTrailingZeros(3) results in
/// BigDecimal('1234.56789').</para></remarks>
function RemoveTrailingZeros(TargetScale: Integer): BigDecimal;
/// <summary>Returns the square root of the current BigDecimal, with the given precision.</summary>
function Sqrt(Precision: Integer): BigDecimal; overload;
/// <summary>Returns the square root of the current BigDecimal, with the default precision.</summary>
function Sqrt: BigDecimal; overload;
/// <summary>Returns the integer power of the current BigDecimal, with unlimited precision.</summary>
function IntPower(Exponent: Integer): BigDecimal; overload;
/// <summary>Returns the integer power of the current BigDecimal, with the given precision.</summary>
function IntPower(Exponent, Precision: Integer): BigDecimal; overload;
/// <summary>Returns the square of the current BigDecimal.</summary>
function Sqr: BigDecimal; overload;
/// <summary>Returns the unit of least precision of the current BigDecimal.</summary>
function ULP: BigDecimal;
/// <summary>Returns a plain string of the BigDecimal value. This is sometimes called 'decimal notation', and
/// shows the value without the use of exponents.</summary>
function ToPlainString: string; overload;
function ToPlainString(const Settings: TFormatSettings): string; overload;
/// <summary>Returns a plain string under certain conditions, otherwise returns scientific notation.</summary>
/// <remarks>This does not use FormatSettings. The output is roundtrip, so it is a valid string that can be
/// parsed using Parse() or TryParse().</remarks>
function ToString: string; overload;
/// <summary>Returns a plain string under certain conditions, otherwise returns scientific notation.</summary>
/// <remarks>This uses the given FormatSettings for the decimal point Char.</remarks>
function ToString(const Settings: TFormatSettings): string; overload;
// -- Class properties --
/// <summary>The rounding mode to be used if no specific mode is given.</summary>
class property DefaultRoundingMode: RoundingMode read FDefaultRoundingMode write FDefaultRoundingMode;
/// <summary>The (maximum) precision to be used for e.g. division if the operation would otherwise result in a
/// non-terminating decimal expansion, i.e. if there is no exact representable decimal result, e.g. when
/// dividing <code>BigDecimal(1) / BigDecimal(3) (= 0.3333333...)</code></summary>
class property DefaultPrecision: Integer read FDefaultPrecision write FDefaultPrecision;
/// <summary>If set to False, division will not try to reduce the trailing zeros to match the
/// preferred scale. That is faster, but usually produces bigger decimals</summary>
class property ReduceTrailingZeros: Boolean read FReduceTrailingZeros write FReduceTrailingZeros;
/// <summary>The string to be used to delimit the exponent part in scientific notation output.</summary>
/// <remarks>Currently, only 'e' and 'E' are allowed. Setting any other value will be ignored. The default is 'e',
/// because a lower case letter 'e' is usually more easily distinguished between digits '0'..'9'.</remarks>
class property ExponentDelimiter: Char read FExponentDelimiter write SetExponentDelimiter;
/// <summary>BigDecimal with value -1: unscaled value = -1, scale = 0.</summary>
class property MinusOne: BigDecimal read FMinusOne;
/// <summary>BigDecimal with value 0: unscaled value = 0, scale = 0.</summary>
class property Zero: BigDecimal read FZero;
/// <summary>BigDecimal with value 1: unscaled value = 1, scale = 0.</summary>
class property One: BigDecimal read FOne;
/// <summary>BigDecimal with value 2: unscaled value = 2, scale = 0.</summary>
class property Two: BigDecimal read FTwo;
/// <summary>BigDecimal with value 10: unscaled value = 10, scale = 0.</summary>
class property Ten: BigDecimal read FTen;
/// <summary>BigDecimal with value 0.5: unscaled value = 5, scale = 1.</summary>
class property Half: BigDecimal read FHalf;
/// <summary>BigDecimal with value 0.1: unscaled value = 1, scale = 1.</summary>
class property OneTenth: BigDecimal read FOneTenth;
// -- Instance properties --
/// <summary>The scale of the current BigDecimal. This is the power of ten by which the UnscaledValue must
/// be divided to get the value of the BigDecimal. Negative scale values denote multiplying by a
/// power of ten.</summary>
/// <remarks>So 1.79e+308 can be stored as UnscaledValue = 179 and Scale = -306, requiring only a small BigInteger
/// with a precision of 3, and not a large one of 308 digits.</remarks>
property Scale: Integer read FScale;
/// <summary>The unscaled value of the current BigDecimal. This is the BigInteger than contains the
/// significant digits of the BigDecimal. It is then scaled (in powers of ten) by Scale.</summary>
property UnscaledValue: BigInteger read FValue;
end;
{$HPPEMIT END '#include "Velthuis.BigDecimals.operators.hpp"'}
implementation
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
uses
Velthuis.FloatUtils, Velthuis.Numerics, Velthuis.StrConsts;
var
PowersOfTen: TArray<BigInteger>;
function InvariantSettings: TFormatSettings;
{$IF RTLVersion >= 29.0}
begin
// XE8 and higher
Result := TFormatSettings.Invariant;
end;
{$ELSE}
const
Settings: TFormatSettings =
(
CurrencyString: #$00A4;
CurrencyFormat: 0;
CurrencyDecimals: 2;
DateSeparator: '/';
TimeSeparator: ':';
ListSeparator: ',';
ShortDateFormat: 'MM/dd/yyyy';
LongDateFormat: 'dddd, dd MMMMM yyyy HH:mm:ss';
TimeAMString: 'AM';
TimePMString: 'PM';
ShortTimeFormat: 'HH:mm';
LongTimeFormat: 'HH:mm:ss';
ShortMonthNames: ('Jan', 'Feb', 'Mar', 'Apr', 'May,', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
LongMonthNames: ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December');
ShortDayNames: ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
LongDayNames: ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
ThousandSeparator: ',';
DecimalSeparator: '.';
TwoDigitYearCenturyWindow: 50;
NegCurrFormat: 0;
);
begin
Result := Settings;
end;
{$IFEND}
{ BigDecimal }
function BigDecimal.Abs: BigDecimal;
begin
if Self.FValue.IsNegative then
Result := -Self
else
Result := Self;
end;
class function BigDecimal.Abs(const Value: BigDecimal): BigDecimal;
begin
Result := Value.Abs;
end;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// Adding and subtracting is easy: the operand with the lowest scale is scaled up to the scale of the //
// other operand. Then the unscaled values (FValue members) can be added or subtracted respectively. //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////////////
class function BigDecimal.Add(const Left, Right: BigDecimal): BigDecimal;
var
L, R: BigInteger;
begin
Result.Init;
if Left.IsZero then
if Right.IsZero then
Exit(BigDecimal.Zero)
else
Exit(Right)
else if Right.IsZero then
Exit(Left);
if Left.Scale > Right.Scale then
begin
L := Left.FValue;
R := Right.FValue * GetPowerOfTen(Left.Scale - Right.Scale);
Result.FScale := Left.FScale;
end
else
begin
L := Left.FValue * GetPowerOfTen(Right.Scale - Left.Scale);
R := Right.FValue;
Result.FScale := Right.FScale;
end;
Result.FValue := L + R;
end;
class operator BigDecimal.Add(const Left, Right: BigDecimal): BigDecimal;
begin
Result := Add(Left, Right);
end;
////////////////////////////////////////////////////
// //
// See comment on rounding near RoundToScale(). //
// //
////////////////////////////////////////////////////
class procedure BigDecimal.AdjustForRoundingMode(var Quotient: BigInteger; const Divisor, Remainder: BigInteger; Sign: Integer; Mode: RoundingMode);
begin
if not Remainder.IsZero then
case Mode of
rmUp: // 1.7x --> 1.8, -1.7x --> -1.8
Inc(Quotient);
rmDown: // 1.7x --> 1.7, -1.7x --> -1.7
; // No action required; truncation is default.
rmCeiling: // 1.7x --> 1.8, -1.7x --> -1.7
if Sign >= 0 then
Inc(Quotient);
rmFloor: // 1.7x --> 1.7, -1.7x --> -1.8
if Sign <= 0 then
Inc(Quotient);
rmNearestUp, rmNearestDown, rmNearestEven:
if Remainder + Remainder > Divisor then // 1.78 --> 1.8, 1.72 --> 1.7, 1.75 --> see next
Inc(Quotient)
else if Remainder + Remainder = Divisor then // the "Half" condition.
if (Mode = rmNearestUp) or ((Mode = rmNearestEven) and not Quotient.IsEven) then
Inc(Quotient);
rmUnnecessary: // No remainder allowed.
Error(ecRounding, []);
end;
end;
{$IFDEF HasExtended}
function BigDecimal.AsExtended: Extended;
begin
Result := Extended(Self);
if IsInfinite(Result) then
Error(ecConversion, ['BigDecimal', 'Extended']);
end;
{$ENDIF}
function BigDecimal.AsDouble: Double;
begin
Result := Double(Self);