-
Notifications
You must be signed in to change notification settings - Fork 4
/
decimal.go
1631 lines (1343 loc) · 40.3 KB
/
decimal.go
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
package udecimal
import (
"fmt"
"math"
"math/big"
"strconv"
)
var (
// defaultPrec is the default number of digits after the decimal point
// if not specified
defaultPrec uint8 = 19
// maxPrec is the maximum number of digits after the decimal point
maxPrec uint8 = 19
// maxStrLen is the maximum length of string input when using Parse/MustParse
// set it to 200 so string length value can fit in 1 byte (for MarshalBinary).
// Also such that big number (more than 200 digits) is unrealistic in financial system
// which this library is mainly designed for
maxStrLen = 200
)
// pre-computed values
var pow10 = [39]u128{
{lo: 1}, // 10^0
{lo: 10}, // 10^1
{lo: 1e2}, // 10^2
{lo: 1e3}, // 10^3
{lo: 1e4}, // 10^4
{lo: 1e5}, // 10^5
{lo: 1e6}, // 10^6
{lo: 1e7}, // 10^7
{lo: 1e8}, // 10^8
{lo: 1e9}, // 10^9
{lo: 1e10}, // 10^10
{lo: 1e11}, // 10^11
{lo: 1e12}, // 10^12
{lo: 1e13}, // 10^13
{lo: 1e14}, // 10^14
{lo: 1e15}, // 10^15
{lo: 1e16}, // 10^16
{lo: 1e17}, // 10^17
{lo: 1e18}, // 10^18
{lo: 1e19}, // 10^19
{lo: 7_766_279_631_452_241_920, hi: 5}, // 10^20
{lo: 3_875_820_019_684_212_736, hi: 54}, // 10^21
{lo: 1_864_712_049_423_024_128, hi: 542}, // 10^22
{lo: 200_376_420_520_689_664, hi: 5_421}, // 10^23
{lo: 2_003_764_205_206_896_640, hi: 54_210}, // 10^24
{lo: 1_590_897_978_359_414_784, hi: 542_101}, // 10^25
{lo: 15_908_979_783_594_147_840, hi: 5_421_010}, // 10^26
{lo: 11_515_845_246_265_065_472, hi: 54_210_108}, // 10^27
{lo: 4_477_988_020_393_345_024, hi: 542_101_086}, // 10^28
{lo: 7_886_392_056_514_347_008, hi: 5_421_010_862}, // 10^29
{lo: 5_076_944_270_305_263_616, hi: 54_210_108_624}, // 10^30
{lo: 1_387_595_455_563_353_2928, hi: 542_101_086_242}, // 10^31
{lo: 9_632_337_040_368_467_968, hi: 5_421_010_862_427}, // 10^32
{lo: 4_089_650_035_136_921_600, hi: 54_210_108_624_275}, // 10^33
{lo: 4_003_012_203_950_112_768, hi: 542_101_086_242_752}, // 10^34
{lo: 3_136_633_892_082_024_448, hi: 5_421_010_862_427_522}, // 10^35
{lo: 12_919_594_847_110_692_864, hi: 54_210_108_624_275_221}, // 10^36
{lo: 68_739_955_140_067_328, hi: 542_101_086_242_752_217}, // 10^37
{lo: 687_399_551_400_673_280, hi: 5_421_010_862_427_522_170}, // 10^38
}
var pow10Big = [20]*big.Int{
big.NewInt(1), // 10^0
big.NewInt(10), // 10^1
big.NewInt(1e2), // 10^2
big.NewInt(1e3), // 10^3
big.NewInt(1e4), // 10^4
big.NewInt(1e5), // 10^5
big.NewInt(1e6), // 10^6
big.NewInt(1e7), // 10^7
big.NewInt(1e8), // 10^8
big.NewInt(1e9), // 10^9
big.NewInt(1e10), // 10^10
big.NewInt(1e11), // 10^11
big.NewInt(1e12), // 10^12
big.NewInt(1e13), // 10^13
big.NewInt(1e14), // 10^14
big.NewInt(1e15), // 10^15
big.NewInt(1e16), // 10^16
big.NewInt(1e17), // 10^17
big.NewInt(1e18), // 10^18
pow10[19].ToBigInt(), // 10^19
}
var (
errOverflow = fmt.Errorf("overflow")
// ErrPrecOutOfRange is returned when the decimal precision is greater than the default precision
// default precision can be configured using SetDefaultPrecision, and its value is up to 19
ErrPrecOutOfRange = fmt.Errorf("precision out of range. Only support maximum %d digits after the decimal point", defaultPrec)
// ErrEmptyString is returned when the input string is empty
ErrEmptyString = fmt.Errorf("parse empty string")
// ErrMaxStrLen is returned when the input string exceeds the maximum length
// Maximum length is arbitrarily set to 200 so string length value can fit in 1 byte (for MarshalBinary).
// Also such that big number (more than 200 digits) is unrealistic in financial system
// which this library is mainly designed for.
ErrMaxStrLen = fmt.Errorf("string input exceeds maximum length %d", maxStrLen)
// ErrInvalidFormat is returned when the input string is not in the correct format
// It doesn't support scientific notation, such as 1e-2, 1.23e4, etc.
ErrInvalidFormat = fmt.Errorf("invalid format")
// ErrDivideByZero is returned when dividing by zero
ErrDivideByZero = fmt.Errorf("can't divide by zero")
// ErrSqrtNegative is returned when calculating square root of negative number
ErrSqrtNegative = fmt.Errorf("can't calculate square root of negative number")
// ErrInvalidBinaryData is returned when unmarshalling invalid binary data
// The binary data should follow the format as described in MarshalBinary
ErrInvalidBinaryData = fmt.Errorf("invalid binary data")
// ErrZeroPowNegative is returned when raising zero to a negative power
ErrZeroPowNegative = fmt.Errorf("can't raise zero to a negative power")
// ErrExponentTooLarge is returned when the exponent is too large and becomes impractical.
ErrExponentTooLarge = fmt.Errorf("exponent is too large. Must be less than or equal math.MaxInt32")
// ErrIntPartOverflow is returned when the integer part of the decimal is too large to fit in int64
ErrIntPartOverflow = fmt.Errorf("integer part is too large to fit in int64")
)
var (
Zero = Decimal{}
One = MustFromInt64(1, 0)
oneUnit = MustFromUint64(1, 19)
)
// Decimal represents a fixed-point decimal number.
// The number is represented as a struct with three fields: coef, neg, and prec.
//
// - coef: the coefficient of the decimal number
// - neg: true if the number is negative
// - prec: the number of digits after the decimal point (0 to 19)
//
// Decimal numbers are immutable and can be used in arithmetic operations such as addition, subtraction, multiplication, and division.
type Decimal struct {
coef bint
neg bool // true if number is negative
prec uint8
}
// SetDefaultPrecision changes the default precision for decimal numbers in the package.
// Max precision is 19 and is also default.
//
// This function is particularly useful when you want to have your precision of the deicmal smaller than 19
// across the whole application. It should be called only once at the beginning of your application
//
// Panics if the new precision is greater than 19 (maxPrec) or new precision is 0
func SetDefaultPrecision(prec uint8) {
if prec > maxPrec {
panic(fmt.Sprintf("precision out of range. Only allow maximum %d digits after the decimal points", maxPrec))
}
if prec == 0 {
panic("prec must be greater than 0")
}
defaultPrec = prec
}
// NewFromHiLo returns a decimal from 128-bit unsigned integer (hi,lo)
func NewFromHiLo(neg bool, hi uint64, lo uint64, prec uint8) (Decimal, error) {
if prec > defaultPrec {
return Decimal{}, ErrPrecOutOfRange
}
coef := u128{hi: hi, lo: lo}
return newDecimal(neg, bintFromU128(coef), prec), nil
}
// newDecimal return the decimal.
// This function should be used internally to create a new decimal
// to ensure the Zero value is consistent and avoid unexpected cases.
func newDecimal(neg bool, coef bint, prec uint8) Decimal {
if coef.IsZero() {
// make Zero consistent and avoid unexpected cases, such as:
// - coef = 0 and neg is true
// - coef = 0 and prec != 0
// These cases results in incorrect comparison between zero values
return Zero
}
return Decimal{neg: neg, coef: coef, prec: prec}
}
// NewFromUint64 returns a decimal which equals to coef / 10^prec and coef is an uint64
// Trailing zeros wll be removed and the prec will also be adjusted
func NewFromUint64(coef uint64, prec uint8) (Decimal, error) {
if prec > defaultPrec {
return Decimal{}, ErrPrecOutOfRange
}
return newDecimal(false, bintFromU64(coef), prec), nil
}
// MustFromUint64 similars to NewFromUint64, but panics instead of returning error
func MustFromUint64(coef uint64, prec uint8) Decimal {
d, err := NewFromUint64(coef, prec)
if err != nil {
panic(err)
}
return d
}
// NewFromInt64 returns a decimal which equals to coef / 10^prec and coef is an int64.
// Trailing zeros wll be removed and the prec will also be adjusted
func NewFromInt64(coef int64, prec uint8) (Decimal, error) {
var neg bool
if coef < 0 {
neg = true
coef = -coef
}
if prec > defaultPrec {
return Decimal{}, ErrPrecOutOfRange
}
//nolint:gosec // coef is positive, so it's safe to convert to uint64
return newDecimal(neg, bintFromU64(uint64(coef)), prec), nil
}
// MustFromInt64 similars to NewFromInt64, but panics instead of returning error
func MustFromInt64(coef int64, prec uint8) Decimal {
d, err := NewFromInt64(coef, prec)
if err != nil {
panic(err)
}
return d
}
// NewFromFloat64 returns a decimal from float64.
//
// **NOTE**: you'll expect to lose some precision for this method due to FormatFloat. See: https://github.com/golang/go/issues/29491
//
// This method is only suitable for small numbers with low precision. e.g. 1.0001, 0.0001, -123.456, -1000000.123456.
// You should avoid using this method if your input number has high precision.
//
// Returns error when:
// 1. f is NaN or Inf
// 2. error when parsing float to string and then to decimal
func NewFromFloat64(f float64) (Decimal, error) {
if math.IsNaN(f) || math.IsInf(f, 0) {
return Decimal{}, fmt.Errorf("%w: can't parse float '%v' to Decimal", ErrInvalidFormat, f)
}
s := strconv.FormatFloat(f, 'f', -1, 64)
d, err := Parse(s)
if err != nil {
return Decimal{}, fmt.Errorf("can't parse float: %w", err)
}
return d, nil
}
// MustFromFloat64 similars to NewFromFloat64, but panics instead of returning error
func MustFromFloat64(f float64) Decimal {
d, err := NewFromFloat64(f)
if err != nil {
panic(err)
}
return d
}
// Int64 returns the integer part of the decimal.
// Return error if the decimal is too large to fit in int64.
func (d Decimal) Int64() (int64, error) {
d1 := d.Trunc(0)
if d1.coef.overflow() {
return 0, ErrIntPartOverflow
}
if d1.coef.u128.Cmp64(math.MaxInt64) > 0 {
return 0, ErrIntPartOverflow
}
//nolint:gosec // can be safely converted as we already checked if coef.u128 is less than math.MaxInt64 above
int64Part := int64(d1.coef.u128.lo)
if d1.neg {
int64Part = -int64Part
}
return int64Part, nil
}
// InexactFloat64 returns the float64 representation of the decimal.
// The result may not be 100% accurate due to the limitation of float64 (less decimal precision).
//
// Caution: this method will not return the exact number if the decimal is too large.
//
// e.g. 123456789012345678901234567890123456789.9999999999999999999 -> 123456789012345680000000000000000000000
func (d Decimal) InexactFloat64() float64 {
f, _ := strconv.ParseFloat(d.String(), 64)
return f
}
// Parse parses a number in string to a decimal.
// The string must be in the format of: [+-]d{1,19}[.d{1,19}]
//
// Returns error if:
// 1. empty/invalid string
// 2. the number has more than 19 digits after the decimal point
// 3. string length exceeds maxStrLen (which is 200 characters. See [ErrMaxStrLen] for more details)
func Parse(s string) (Decimal, error) {
return parseBytes(unsafeStringToBytes(s))
}
func parseBytes(b []byte) (Decimal, error) {
neg, bint, prec, err := parseBint(b)
if err != nil {
return Decimal{}, err
}
return newDecimal(neg, bint, prec), nil
}
// MustParse similars to Parse, but pacnis instead of returning error.
func MustParse(s string) Decimal {
d, err := Parse(s)
if err != nil {
panic(err)
}
return d
}
// Add returns d + e
func (d Decimal) Add(e Decimal) Decimal {
dcoef, ecoef := d.coef, e.coef
var (
prec uint8
)
switch {
case d.prec == e.prec:
prec = d.prec
case d.prec > e.prec:
prec = d.prec
ecoef = ecoef.Mul(bintFromU128(pow10[d.prec-e.prec]))
case d.prec < e.prec:
prec = e.prec
dcoef = dcoef.Mul(bintFromU128(pow10[e.prec-d.prec]))
}
if d.neg == e.neg {
return newDecimal(d.neg, dcoef.Add(ecoef), prec)
}
// different sign
switch dcoef.Cmp(ecoef) {
case 1:
// dcoef > ecoef, subtract can't overflow
coef, _ := dcoef.Sub(ecoef)
return newDecimal(d.neg, coef, prec)
default:
// dcoef <= ecoef
coef, _ := ecoef.Sub(dcoef)
return newDecimal(e.neg, coef, prec)
}
}
// Add64 returns d + e where e is a uint64
func (d Decimal) Add64(e uint64) Decimal {
ecoef := bintFromU64(e).Mul(bintFromU128(pow10[d.prec]))
if d.neg {
var (
dcoef bint
neg bool
)
if d.coef.GT(ecoef) {
// can ignore the error as we already check if dcoef > ecoef
dcoef, _ = d.coef.Sub(ecoef)
neg = true
} else {
dcoef, _ = ecoef.Sub(d.coef)
neg = false
}
return newDecimal(neg, dcoef, d.prec)
}
dcoef := d.coef.Add(ecoef)
return newDecimal(false, dcoef, d.prec)
}
// Sub returns d - e
func (d Decimal) Sub(e Decimal) Decimal {
dcoef, ecoef := d.coef, e.coef
var (
prec uint8
)
switch {
case d.prec == e.prec:
prec = d.prec
case d.prec > e.prec:
prec = d.prec
ecoef = ecoef.Mul(bintFromU128(pow10[d.prec-e.prec]))
case d.prec < e.prec:
prec = e.prec
dcoef = dcoef.Mul(bintFromU128(pow10[e.prec-d.prec]))
}
if d.neg != e.neg {
// different sign
coef := dcoef.Add(ecoef)
return newDecimal(d.neg, coef, prec)
}
// same sign
switch dcoef.Cmp(ecoef) {
case 1:
// dcoef > ecoef, subtract can't overflow
coef, _ := dcoef.Sub(ecoef)
return newDecimal(d.neg, coef, prec)
default:
// dcoef <= ecoef
coef, _ := ecoef.Sub(dcoef)
return newDecimal(!d.neg, coef, prec)
}
}
// Sub64 returns d - e where e is a uint64
func (d Decimal) Sub64(e uint64) Decimal {
ecoef := bintFromU64(e).Mul(bintFromU128(pow10[d.prec]))
if !d.neg {
var (
dcoef bint
neg bool
)
if d.coef.GT(ecoef) {
// dcoef > ecoef, subtract can't overflow
dcoef, _ = d.coef.Sub(ecoef)
neg = false
} else {
dcoef, _ = ecoef.Sub(d.coef)
neg = true
}
return newDecimal(neg, dcoef, d.prec)
}
return newDecimal(true, d.coef.Add(ecoef), d.prec)
}
// Mul returns d * e.
// The result will have at most defaultPrec digits after the decimal point.
func (d Decimal) Mul(e Decimal) Decimal {
prec := d.prec + e.prec
neg := d.neg != e.neg
v, err := tryMulU128(d, e, neg, prec)
if err == nil {
return v
}
// overflow, try with *big.Int
dBig := d.coef.GetBig()
eBig := e.coef.GetBig()
dBig.Mul(dBig, eBig)
if prec <= defaultPrec {
return newDecimal(neg, bintFromBigInt(dBig), prec)
}
q, _ := new(big.Int).QuoRem(dBig, pow10[prec-defaultPrec].ToBigInt(), new(big.Int))
return newDecimal(neg, bintFromBigInt(q), defaultPrec)
}
func tryMulU128(d, e Decimal, neg bool, prec uint8) (Decimal, error) {
if d.coef.overflow() || e.coef.overflow() {
return Decimal{}, errOverflow
}
rcoef := d.coef.u128.MulToU256(e.coef.u128)
if prec <= defaultPrec {
if !rcoef.carry.IsZero() {
return Decimal{}, errOverflow
}
coef := u128{hi: rcoef.hi, lo: rcoef.lo}
return newDecimal(neg, bintFromU128(coef), prec), nil
}
q, _, err := rcoef.fastQuo(pow10[prec-defaultPrec])
if err != nil {
return Decimal{}, err
}
return newDecimal(neg, bintFromU128(q), defaultPrec), nil
}
// Mul64 returns d * e where e is a uint64.
// The result will have at most defaultPrec digits after the decimal point.
func (d Decimal) Mul64(v uint64) Decimal {
if v == 0 {
return Decimal{}
}
if v == 1 {
return d
}
if !d.coef.overflow() {
coef, err := d.coef.u128.Mul64(v)
if err == nil {
return newDecimal(d.neg, bintFromU128(coef), d.prec)
}
}
// overflow, try with *big.Int
dBig := d.coef.GetBig()
dBig.Mul(dBig, new(big.Int).SetUint64(v))
return newDecimal(d.neg, bintFromBigInt(dBig), d.prec)
}
// Div returns d / e.
// If the result has more than defaultPrec fraction digits, it will be truncated to defaultPrec digits.
//
// Returns divide by zero error when e is zero
func (d Decimal) Div(e Decimal) (Decimal, error) {
if e.coef.IsZero() {
return Decimal{}, ErrDivideByZero
}
neg := d.neg != e.neg
q, err := tryDivU128(d, e, neg)
if err == nil {
return q, nil
}
// Need to multiply divident with factor
// to make sure the total decimal number after the decimal point is defaultPrec
factor := defaultPrec - (d.prec - e.prec)
// overflow, try with *big.Int
dBig := d.coef.GetBig()
eBig := e.coef.GetBig()
dBig.Mul(dBig, pow10[factor].ToBigInt())
dBig.Div(dBig, eBig)
return newDecimal(neg, bintFromBigInt(dBig), defaultPrec), nil
}
func tryDivU128(d, e Decimal, neg bool) (Decimal, error) {
if d.coef.overflow() || e.coef.overflow() {
return Decimal{}, errOverflow
}
// Need to multiply divident with factor
// to make sure the total decimal number after the decimal point is defaultPrec
factor := defaultPrec - (d.prec - e.prec)
d256 := d.coef.u128.MulToU256(pow10[factor])
quo, _, err := d256.fastQuo(e.coef.u128)
if err != nil {
return Decimal{}, err
}
return newDecimal(neg, bintFromU128(quo), defaultPrec), nil
}
// Div64 returns d / e where e is a uint64.
// If the result has more than defaultPrec fraction digits, it will be truncated to defaultPrec digits.
//
// Returns divide by zero error when e is zero
func (d Decimal) Div64(v uint64) (Decimal, error) {
if v == 0 {
return Decimal{}, ErrDivideByZero
}
if v == 1 {
return d, nil
}
if !d.coef.overflow() {
d256 := d.coef.u128.MulToU256(pow10[defaultPrec-d.prec])
quo, _, err := d256.div192by64(v)
if err == nil {
return newDecimal(d.neg, bintFromU128(quo), defaultPrec), nil
}
// overflow, try with *big.Int
}
// overflow, try with *big.Int
dBig := d.coef.GetBig()
dBig.Mul(dBig, pow10[defaultPrec-d.prec].ToBigInt())
dBig.Div(dBig, new(big.Int).SetUint64(v))
return newDecimal(d.neg, bintFromBigInt(dBig), defaultPrec), nil
}
// QuoRem returns q and r where
// - q = d / e and q is an integer
// - r = d - q * e (r < e and r has the same sign as d)
//
// The implementation is similar to C's fmod function.
// Returns divide by zero error when e is zero
func (d Decimal) QuoRem(e Decimal) (Decimal, Decimal, error) {
if e.coef.IsZero() {
return Decimal{}, Decimal{}, ErrDivideByZero
}
q, r, err := tryQuoRemU128(d, e)
if err == nil {
return q, r, nil
}
factor := max(d.prec, e.prec)
// overflow, try with *big.Int
dBig := d.coef.GetBig()
eBig := e.coef.GetBig()
dBig.Mul(dBig, pow10[factor-d.prec].ToBigInt())
eBig.Mul(eBig, pow10[factor-e.prec].ToBigInt())
qBig, rBig := new(big.Int), new(big.Int)
qBig.QuoRem(dBig, eBig, rBig)
q = newDecimal(d.neg != e.neg, bintFromBigInt(qBig), 0)
r = newDecimal(d.neg, bintFromBigInt(rBig), factor)
return q, r, nil
}
func tryQuoRemU128(d, e Decimal) (Decimal, Decimal, error) {
if d.coef.overflow() || e.coef.overflow() {
return Decimal{}, Decimal{}, errOverflow
}
var (
factor uint8
d256 u256
e128 u128
err error
)
if d.prec == e.prec {
factor = d.prec
d256 = u256{lo: d.coef.u128.lo, hi: d.coef.u128.hi}
e128 = e.coef.u128
} else {
factor = max(d.prec, e.prec)
d256 = d.coef.u128.MulToU256(pow10[factor-d.prec])
// If divisor >= 2^128, we can't use fastQuo and have to fallback to big.Int
e128, err = e.coef.u128.Mul(pow10[factor-e.prec])
if err != nil {
return Decimal{}, Decimal{}, err
}
}
q1, r1, err := d256.fastQuo(e128)
if err != nil {
return Decimal{}, Decimal{}, err
}
q := newDecimal(d.neg != e.neg, bintFromU128(q1), 0)
r := newDecimal(d.neg, bintFromU128(r1), factor)
return q, r, nil
}
// Mod is similar to [Decimal.QuoRem] but only returns the remainder
func (d Decimal) Mod(e Decimal) (Decimal, error) {
_, r, err := d.QuoRem(e)
return r, err
}
// Prec returns decimal precision as an integer
func (d Decimal) Prec() int {
return int(d.prec)
}
// PrecUint returns decimal precision as uint8
// Useful when you want to use the precision
// in other functions like [Decimal.RoundBank] or [Decimal.Trunc] because they accept uint8
//
// Example:
//
// u := MustParse("0.000001")
// d := MustParse("123.4567891") // 123.456, prec = 3
// d = d.Trunc(u.PrecUint()) // 123.456789
func (d Decimal) PrecUint() uint8 {
return d.prec
}
// Cmp compares two decimals d,e and returns:
//
// -1 if d < e
// 0 if d == e
// +1 if d > e
func (d Decimal) Cmp(e Decimal) int {
if d.neg && !e.neg {
return -1
}
if !d.neg && e.neg {
return 1
}
// d.neg = e.neg
if d.neg {
// both are negative, return the opposite
return -d.cmpDecSameSign(e)
}
return d.cmpDecSameSign(e)
}
// Equal reports whether the two decimals d and e are equal.
func (d Decimal) Equal(e Decimal) bool {
return d.Cmp(e) == 0
}
func (d Decimal) cmpDecSameSign(e Decimal) int {
result, err := tryCmpU128(d, e)
if err == nil {
return result
}
// overflow, fallback to big.Int
dBig := d.coef.GetBig()
eBig := e.coef.GetBig()
if d.prec == e.prec {
return dBig.Cmp(eBig)
}
if d.prec < e.prec {
dBig.Mul(dBig, pow10[e.prec-d.prec].ToBigInt())
} else {
eBig.Mul(eBig, pow10[d.prec-e.prec].ToBigInt())
}
return dBig.Cmp(eBig)
}
func tryCmpU128(d, e Decimal) (int, error) {
if d.coef.overflow() || e.coef.overflow() {
return 0, errOverflow
}
if d.prec == e.prec {
return d.coef.u128.Cmp(e.coef.u128), nil
}
// prec is different
// e has more fraction digits
if d.prec < e.prec {
// d has more fraction digits
d256 := d.coef.u128.MulToU256(pow10[e.prec-d.prec])
return d256.cmp128(e.coef.u128), nil
}
// d has more fraction digits
// we need to compare d with e * 10^(d.prec - e.prec)
e256 := e.coef.u128.MulToU256(pow10[d.prec-e.prec])
// remember to reverse the result because e256.cmp128(d.coef) returns the opposite
return -e256.cmp128(d.coef.u128), nil
}
// Rescale returns the decimal with the new prec only if the new prec is greater than the current prec.
// Useful when you want to increase the prec of the decimal for display purposes.
//
// Example:
//
// d := MustParse("123.456") // 123.456, prec = 3
// d.rescale(5) // 123.45600, prec = 5
func (d Decimal) rescale(prec uint8) Decimal {
dTrim := d.trimTrailingZeros()
if prec > maxPrec {
prec = maxPrec
}
if prec <= dTrim.prec {
return dTrim
}
diff := prec - dTrim.prec
coef := dTrim.coef.Mul(bintFromU128(pow10[diff]))
// only this case we're not using newDecimal to apply exact precision to zero value
// this happens when calling StringFixed with 0: 0.StringFixed(5) -> "0.00000"
// If we use newDecimal, the precision will always be 0, then 0.StringFixed(5) -> "0"
return Decimal{neg: dTrim.neg, coef: coef, prec: prec}
}
// Neg returns -d
func (d Decimal) Neg() Decimal {
return newDecimal(!d.neg, d.coef, d.prec)
}
// Abs returns |d|
func (d Decimal) Abs() Decimal {
return newDecimal(false, d.coef, d.prec)
}
// Sign returns:
//
// -1 if d < 0
// 0 if d == 0
// +1 if d > 0
func (d Decimal) Sign() int {
// check this first
// because we allow parsing "-0" into decimal, which results in d.neg = true and d.coef = 0
if d.coef.IsZero() {
return 0
}
if d.neg {
return -1
}
return 1
}
// IsZero returns
//
// true if d == 0
// false if d != 0
func (d Decimal) IsZero() bool {
return d.coef.IsZero()
}
// IsNeg returns
//
// true if d < 0
// false if d >= 0
func (d Decimal) IsNeg() bool {
return d.neg && !d.coef.IsZero()
}
// IsPos returns
//
// true if d > 0
// false if d <= 0
func (d Decimal) IsPos() bool {
return !d.neg && !d.coef.IsZero()
}
// RoundBank uses half up to even (banker's rounding) to round the decimal to the specified prec.
//
// Examples:
//
// RoundBank(1.12345, 4) = 1.1234
// RoundBank(1.12335, 4) = 1.1234
// RoundBank(1.5, 0) = 2
// RoundBank(-1.5, 0) = -2
func (d Decimal) RoundBank(prec uint8) Decimal {
if prec >= d.prec {
return d
}
factor := pow10[d.prec-prec]
lo := factor.lo / 2
if !d.coef.overflow() {
var err error
q, r := d.coef.u128.QuoRem64(factor.lo)
if lo < r || (lo == r && q.lo%2 == 1) {
q, err = q.Add64(1)
}
// no overflow, return the result
if err == nil {
return newDecimal(d.neg, bintFromU128(q), prec)
}
}
// overflow, fallback to big.Int
dBig := d.coef.GetBig()
q, r := new(big.Int).QuoRem(dBig, factor.ToBigInt(), new(big.Int))
loBig := new(big.Int).SetUint64(lo)
if r.Cmp(loBig) > 0 || (r.Cmp(loBig) == 0 && q.Bit(0) == 1) {
q.Add(q, bigOne)
}
return newDecimal(d.neg, bintFromBigInt(q), prec)
}
// RoundAwayFromZero rounds the decimal to the specified prec using AWAY FROM ZERO method (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero).
// If differs from HALF AWAY FROM ZERO in a way that the number is always rounded away from zero (or to infinity) no matter if is 0.5 or not.
// In other libraries or languages, this method is also known as ROUND_UP.
//
// Examples:
//
// Round(1.12, 1) = 1.2
// Round(1.15, 1) = 1.2
// Round(-1.12, 1) = -1.12
// Round(-1.15, 1) = -1.12
func (d Decimal) RoundAwayFromZero(prec uint8) Decimal {
if prec >= d.prec {
return d
}
factor := pow10[d.prec-prec]
if !d.coef.overflow() {
var err error
q, r := d.coef.u128.QuoRem64(factor.lo)
if r != 0 {
q, err = q.Add64(1)
}
if err == nil {
return newDecimal(d.neg, bintFromU128(q), prec)
}
}
// overflow, fallback to big.Int
dBig := d.coef.GetBig()
q, r := new(big.Int).QuoRem(dBig, factor.ToBigInt(), new(big.Int))
if r.Cmp(bigZero) != 0 {
q.Add(q, bigOne)
}
return newDecimal(d.neg, bintFromBigInt(q), prec)
}
// RoundHAZ rounds the decimal to the specified prec using HALF AWAY FROM ZERO method (https://en.wikipedia.org/wiki/Rounding#Rounding_half_away_from_zero).
//
// Examples:
//
// Round(1.12345, 4) = 1.1235
// Round(1.12335, 4) = 1.1234
// Round(1.5, 0) = 2
// Round(-1.5, 0) = -2
func (d Decimal) RoundHAZ(prec uint8) Decimal {
if prec >= d.prec {
return d
}
factor := pow10[d.prec-prec]
half, _ := factor.QuoRem64(2)
if !d.coef.overflow() {
var err error
q, r := d.coef.u128.QuoRem64(factor.lo)
if half.Cmp64(r) <= 0 {
q, err = q.Add64(1)
}
if err == nil {
return newDecimal(d.neg, bintFromU128(q), prec)
}
}
// overflow, fallback to big.Int
dBig := d.coef.GetBig()
q, r := new(big.Int).QuoRem(dBig, factor.ToBigInt(), new(big.Int))
loBig := half.ToBigInt()
if r.Cmp(loBig) >= 0 {
q.Add(q, bigOne)
}
return newDecimal(d.neg, bintFromBigInt(q), prec)
}
// RoundHTZ rounds the decimal to the specified prec using HALF TOWARD ZERO method (https://en.wikipedia.org/wiki/Rounding#Rounding_half_toward_zero).
//
// Examples:
//
// Round(1.12345, 4) = 1.1234
// Round(1.12335, 4) = 1.1233
// Round(1.5, 0) = 1
// Round(-1.5, 0) = -1
func (d Decimal) RoundHTZ(prec uint8) Decimal {
if prec >= d.prec {
return d
}
factor := pow10[d.prec-prec]