-
Notifications
You must be signed in to change notification settings - Fork 12
/
decimal.go
3061 lines (2674 loc) · 75 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 decimal
import (
"database/sql/driver"
"errors"
"fmt"
"math"
"strconv"
)
// Decimal represents a finite floating-point decimal number.
// Its zero value corresponds to the numeric value of 0.
// Decimal is designed to be safe for concurrent use by multiple goroutines.
type Decimal struct {
neg bool // indicates whether the decimal is negative
scale int8 // position of the floating decimal point
coef fint // numeric value without decimal point
}
const (
MaxPrec = 19 // MaxPrec is the maximum length of the coefficient in decimal digits.
MinScale = 0 // MinScale is the minimum number of digits after the decimal point.
MaxScale = 19 // MaxScale is the maximum number of digits after the decimal point.
maxCoef = maxFint // maxCoef is the maximum absolute value of the coefficient, which is equal to (10^MaxPrec - 1).
)
var (
NegOne = MustNew(-1, 0) // NegOne represents the decimal value of -1.
Zero = MustNew(0, 0) // Zero represents the decimal value of 0. For comparison purposes, use the IsZero method.
One = MustNew(1, 0) // One represents the decimal value of 1.
Two = MustNew(2, 0) // Two represents the decimal value of 2.
Ten = MustNew(10, 0) // Ten represents the decimal value of 10.
Hundred = MustNew(100, 0) // Hundred represents the decimal value of 100.
Thousand = MustNew(1_000, 0) // Thousand represents the decimal value of 1,000.
E = MustNew(2_718_281_828_459_045_235, 18) // E represents Euler’s number rounded to 18 digits.
Pi = MustNew(3_141_592_653_589_793_238, 18) // Pi represents the value of π rounded to 18 digits.
errDecimalOverflow = errors.New("decimal overflow")
errInvalidDecimal = errors.New("invalid decimal")
errScaleRange = errors.New("scale out of range")
errInvalidOperation = errors.New("invalid operation")
errInexactDivision = errors.New("inexact division")
errDivisionByZero = errors.New("division by zero")
)
// newUnsafe creates a new decimal without checking the scale and coefficient.
// Use it only if you are absolutely sure that the arguments are valid.
func newUnsafe(neg bool, coef fint, scale int) Decimal {
if coef == 0 {
neg = false
}
//nolint:gosec
return Decimal{neg: neg, coef: coef, scale: int8(scale)}
}
// newSafe creates a new decimal and checks the scale and coefficient.
func newSafe(neg bool, coef fint, scale int) (Decimal, error) {
switch {
case scale < MinScale || scale > MaxScale:
return Decimal{}, errScaleRange
case coef > maxCoef:
return Decimal{}, errDecimalOverflow
}
return newUnsafe(neg, coef, scale), nil
}
// newFromFint creates a new decimal from a uint64 coefficient.
// This method does not use overflowError to return descriptive errors,
// as it must be as fast as possible.
func newFromFint(neg bool, coef fint, scale, minScale int) (Decimal, error) {
var ok bool
// Scale normalization
switch {
case scale < minScale:
coef, ok = coef.lsh(minScale - scale)
if !ok {
return Decimal{}, errDecimalOverflow
}
scale = minScale
case scale > MaxScale:
coef = coef.rshHalfEven(scale - MaxScale)
scale = MaxScale
}
return newSafe(neg, coef, scale)
}
// newFromBint creates a new decimal from a *big.Int coefficient.
// This method uses overflowError to return descriptive errors.
func newFromBint(neg bool, coef *bint, scale, minScale int) (Decimal, error) {
// Overflow validation
prec := coef.prec()
if prec-scale > MaxPrec-minScale {
return Decimal{}, overflowError(prec, scale, minScale)
}
// Scale normalization
switch {
case scale < minScale:
coef.lsh(coef, minScale-scale)
scale = minScale
case scale >= prec && scale > MaxScale: // no integer part
coef.rshHalfEven(coef, scale-MaxScale)
scale = MaxScale
case prec > scale && prec > MaxPrec: // there is an integer part
coef.rshHalfEven(coef, prec-MaxPrec)
scale = MaxPrec - prec + scale
}
// Handling the rare case when rshHalfEven rounded
// a 19-digit coefficient to a 20-digit coefficient.
if coef.hasPrec(MaxPrec + 1) {
return newFromBint(neg, coef, scale, minScale)
}
return newSafe(neg, coef.fint(), scale)
}
func overflowError(gotPrec, gotScale, wantScale int) error {
maxDigits := MaxPrec - wantScale
gotDigits := gotPrec - gotScale
switch wantScale {
case 0:
return fmt.Errorf("%w: the integer part of a %T can have at most %v digits, but it has %v digits", errDecimalOverflow, Decimal{}, maxDigits, gotDigits)
default:
return fmt.Errorf("%w: with %v significant digits after the decimal point, the integer part of a %T can have at most %v digits, but it has %v digits", errDecimalOverflow, wantScale, Decimal{}, maxDigits, gotDigits)
}
}
func unknownOverflowError(wantScale int) error {
maxDigits := MaxPrec - wantScale
switch wantScale {
case 0:
return fmt.Errorf("%w: the integer part of a %T can have at most %v digits, but it has significantly more digits", errDecimalOverflow, Decimal{}, maxDigits)
default:
return fmt.Errorf("%w: with %v significant digits after the decimal point, the integer part of a %T can have at most %v digits, but it has significantly more digits", errDecimalOverflow, wantScale, Decimal{}, maxDigits)
}
}
// New returns a decimal equal to value / 10^scale.
// New keeps trailing zeros in the fractional part to preserve scale.
//
// New returns an error if the scale is negative or greater than [MaxScale].
func New(value int64, scale int) (Decimal, error) {
var coef fint
var neg bool
if value >= 0 {
neg = false
coef = fint(value)
} else {
neg = true
if value == math.MinInt64 {
coef = fint(math.MaxInt64) + 1
} else {
coef = fint(-value)
}
}
return newSafe(neg, coef, scale)
}
// MustNew is like [New] but panics if the decimal cannot be constructed.
// It simplifies safe initialization of global variables holding decimals.
func MustNew(value int64, scale int) Decimal {
d, err := New(value, scale)
if err != nil {
panic(fmt.Sprintf("New(%v, %v) failed: %v", value, scale, err))
}
return d
}
// NewFromInt64 converts a pair of integers, representing the whole and
// fractional parts, to a (possibly rounded) decimal equal to whole + frac / 10^scale.
// NewFromInt64 removes all trailing zeros from the fractional part.
// This method is useful for converting amounts from [protobuf] format.
// See also method [Decimal.Int64].
//
// NewFromInt64 returns an error if:
// - the whole and fractional parts have different signs;
// - the scale is negative or greater than [MaxScale];
// - frac / 10^scale is not within the range (-1, 1).
//
// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto
func NewFromInt64(whole, frac int64, scale int) (Decimal, error) {
// Whole
d, err := New(whole, 0)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err)
}
// Fraction
f, err := New(frac, scale)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err)
}
if !f.IsZero() {
if !d.IsZero() && d.Sign() != f.Sign() {
return Decimal{}, fmt.Errorf("converting integers: inconsistent signs")
}
if !f.WithinOne() {
return Decimal{}, fmt.Errorf("converting integers: inconsistent fraction")
}
f = f.Trim(0)
d, err = d.Add(f)
if err != nil {
return Decimal{}, fmt.Errorf("converting integers: %w", err)
}
}
return d, nil
}
// NewFromFloat64 converts a float to a (possibly rounded) decimal.
// See also method [Decimal.Float64].
//
// NewFromFloat64 returns an error if:
// - the float is a special value (NaN or Inf);
// - the integer part of the result has more than [MaxPrec] digits.
func NewFromFloat64(f float64) (Decimal, error) {
// Float
if math.IsNaN(f) || math.IsInf(f, 0) {
return Decimal{}, fmt.Errorf("converting float: special value %v", f)
}
s := strconv.FormatFloat(f, 'f', -1, 64)
// Decimal
d, err := Parse(s)
if err != nil {
return Decimal{}, fmt.Errorf("converting float: %w", err)
}
return d, nil
}
// Zero returns a decimal with a value of 0, having the same scale as decimal d.
// See also methods [Decimal.One], [Decimal.ULP].
func (d Decimal) Zero() Decimal {
return newUnsafe(false, 0, d.Scale())
}
// One returns a decimal with a value of 1, having the same scale as decimal d.
// See also methods [Decimal.Zero], [Decimal.ULP].
func (d Decimal) One() Decimal {
return newUnsafe(false, pow10[d.Scale()], d.Scale())
}
// ULP (Unit in the Last Place) returns the smallest representable positive
// difference between two decimals with the same scale as decimal d.
// It can be useful for implementing rounding and comparison algorithms.
// See also methods [Decimal.Zero], [Decimal.One].
func (d Decimal) ULP() Decimal {
return newUnsafe(false, 1, d.Scale())
}
// Parse converts a string to a (possibly rounded) decimal.
// The input string must be in one of the following formats:
//
// 1.234
// -1234
// +0.000001234
// 1.83e5
// 0.22e-9
//
// The formal EBNF grammar for the supported format is as follows:
//
// sign ::= '+' | '-'
// digits ::= { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }
// significand ::= digits '.' digits | '.' digits | digits '.' | digits
// exponent ::= ('e' | 'E') [sign] digits
// numeric-string ::= [sign] significand [exponent]
//
// Parse removes leading zeros from the integer part of the input string,
// but tries to maintain trailing zeros in the fractional part to preserve scale.
//
// Parse returns an error if:
// - the string contains any whitespaces;
// - the string is longer than 330 bytes;
// - the exponent is less than -330 or greater than 330;
// - the string does not represent a valid decimal number;
// - the integer part of the result has more than [MaxPrec] digits.
func Parse(s string) (Decimal, error) {
return ParseExact(s, 0)
}
// ParseExact is similar to [Parse], but it allows you to specify how many digits
// after the decimal point should be considered significant.
// If any of the significant digits are lost during rounding, the method will return an error.
// This method is useful for parsing monetary amounts, where the scale should be
// equal to or greater than the currency's scale.
func ParseExact(s string, scale int) (Decimal, error) {
if len(s) > 330 {
return Decimal{}, fmt.Errorf("parsing decimal: %w", errInvalidDecimal)
}
if scale < MinScale || scale > MaxScale {
return Decimal{}, fmt.Errorf("parsing decimal: %w", errScaleRange)
}
d, err := parseFint(s, scale)
if err != nil {
d, err = parseBint(s, scale)
if err != nil {
return Decimal{}, fmt.Errorf("parsing decimal: %w", err)
}
}
return d, nil
}
// parseFint parses a decimal string using uint64 arithmetic.
// parseFint does not support exponential notation to make it as fast as possible.
//
//nolint:gocyclo
func parseFint(s string, minScale int) (Decimal, error) {
var pos int
width := len(s)
// Sign
var neg bool
switch {
case pos == width:
// skip
case s[pos] == '-':
neg = true
pos++
case s[pos] == '+':
pos++
}
// Coefficient
var coef fint
var scale int
var hasCoef, ok bool
// Integer
for pos < width && s[pos] >= '0' && s[pos] <= '9' {
coef, ok = coef.fsa(1, s[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow
}
pos++
hasCoef = true
}
// Fraction
if pos < width && s[pos] == '.' {
pos++
for pos < width && s[pos] >= '0' && s[pos] <= '9' {
coef, ok = coef.fsa(1, s[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow
}
pos++
scale++
hasCoef = true
}
}
if pos != width {
return Decimal{}, fmt.Errorf("%w: unexpected character %q", errInvalidDecimal, s[pos])
}
if !hasCoef {
return Decimal{}, fmt.Errorf("%w: no coefficient", errInvalidDecimal)
}
return newFromFint(neg, coef, scale, minScale)
}
// parseBint parses a decimal string using *big.Int arithmetic.
// parseBint supports exponential notation.
//
//nolint:gocyclo
func parseBint(s string, minScale int) (Decimal, error) {
var pos int
width := len(s)
// Sign
var neg bool
switch {
case pos == width:
// skip
case s[pos] == '-':
neg = true
pos++
case s[pos] == '+':
pos++
}
// Coefficient
bcoef := getBint()
defer putBint(bcoef)
bcoef.setFint(0)
var fcoef fint
var shift, scale int
var hasCoef, ok bool
// Algorithm:
// 1. Add as many digits as possible to the uint64 coefficient (fast).
// 2. Once the uint64 coefficient has reached its maximum value,
// add it to the *big.Int coefficient (slow).
// 3. Repeat until all digits are processed.
// Integer
for pos < width && s[pos] >= '0' && s[pos] <= '9' {
fcoef, ok = fcoef.fsa(1, s[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow // Should never happen
}
pos++
shift++
hasCoef = true
if fcoef.hasPrec(MaxPrec) {
bcoef.fsa(bcoef, shift, fcoef)
fcoef, shift = 0, 0
}
}
// Fraction
if pos < width && s[pos] == '.' {
pos++
for pos < width && s[pos] >= '0' && s[pos] <= '9' {
fcoef, ok = fcoef.fsa(1, s[pos]-'0')
if !ok {
return Decimal{}, errDecimalOverflow // Should never happen
}
pos++
scale++
shift++
hasCoef = true
if fcoef.hasPrec(MaxPrec) {
bcoef.fsa(bcoef, shift, fcoef)
fcoef, shift = 0, 0
}
}
}
if shift > 0 {
bcoef.fsa(bcoef, shift, fcoef)
}
// Exponent
var exp int
var eneg, hasExp, hasE bool
if pos < width && (s[pos] == 'e' || s[pos] == 'E') {
pos++
hasE = true
// Sign
switch {
case pos == width:
// skip
case s[pos] == '-':
eneg = true
pos++
case s[pos] == '+':
pos++
}
// Integer
for pos < width && s[pos] >= '0' && s[pos] <= '9' {
exp = exp*10 + int(s[pos]-'0')
if exp > 330 {
return Decimal{}, errInvalidDecimal
}
pos++
hasExp = true
}
}
if pos != width {
return Decimal{}, fmt.Errorf("%w: unexpected character %q", errInvalidDecimal, s[pos])
}
if !hasCoef {
return Decimal{}, fmt.Errorf("%w: no coefficient", errInvalidDecimal)
}
if hasE && !hasExp {
return Decimal{}, fmt.Errorf("%w: no exponent", errInvalidDecimal)
}
if eneg {
scale = scale + exp
} else {
scale = scale - exp
}
return newFromBint(neg, bcoef, scale, minScale)
}
// MustParse is like [Parse] but panics if the string cannot be parsed.
// It simplifies safe initialization of global variables holding decimals.
func MustParse(s string) Decimal {
d, err := Parse(s)
if err != nil {
panic(fmt.Sprintf("Parse(%q) failed: %v", s, err))
}
return d
}
// String implements the [fmt.Stringer] interface and returns
// a string representation of the decimal.
// The returned string does not use scientific or engineering notation and is
// formatted according to the following formal EBNF grammar:
//
// sign ::= '-'
// digits ::= { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }
// significand ::= digits '.' digits | digits
// numeric-string ::= [sign] significand
//
// See also method [Decimal.Format].
//
// [fmt.Stringer]: https://pkg.go.dev/fmt#Stringer
func (d Decimal) String() string {
var buf [24]byte
pos := len(buf) - 1
coef := d.Coef()
scale := d.Scale()
// Coefficient
for {
buf[pos] = byte(coef%10) + '0'
pos--
coef /= 10
if scale > 0 {
scale--
// Decimal point
if scale == 0 {
buf[pos] = '.'
pos--
// Leading 0
if coef == 0 {
buf[pos] = '0'
pos--
}
}
}
if coef == 0 && scale == 0 {
break
}
}
// Sign
if d.IsNeg() {
buf[pos] = '-'
pos--
}
return string(buf[pos+1:])
}
// Float64 returns the nearest binary floating-point number rounded
// using [rounding half to even] (banker's rounding).
// See also constructor [NewFromFloat64].
//
// This conversion may lose data, as float64 has a smaller precision
// than the decimal type.
//
// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even
func (d Decimal) Float64() (f float64, ok bool) {
s := d.String()
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, false
}
return f, true
}
// Int64 returns a pair of integers representing the whole and
// (possibly rounded) fractional parts of the decimal.
// If given scale is greater than the scale of the decimal, then the fractional part
// is zero-padded to the right.
// If given scale is smaller than the scale of the decimal, then the fractional part
// is rounded using [rounding half to even] (banker's rounding).
// The relationship between the decimal and the returned values can be expressed
// as d = whole + frac / 10^scale.
// This method is useful for converting amounts to [protobuf] format.
// See also constructor [NewFromInt64].
//
// If the result cannot be represented as a pair of int64 values,
// then false is returned.
//
// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even
// [protobuf]: https://github.com/googleapis/googleapis/blob/master/google/type/money.proto
func (d Decimal) Int64(scale int) (whole, frac int64, ok bool) {
if scale < MinScale || scale > MaxScale {
return 0, 0, false
}
x := d.coef
y := pow10[d.Scale()]
if scale < d.Scale() {
x = x.rshHalfEven(d.Scale() - scale)
y = pow10[scale]
}
q, r, ok := x.quoRem(y)
if !ok {
return 0, 0, false // Should never happen
}
if scale > d.Scale() {
r, ok = r.lsh(scale - d.Scale())
if !ok {
return 0, 0, false // Should never happen
}
}
if d.IsNeg() {
if q > -math.MinInt64 || r > -math.MinInt64 {
return 0, 0, false
}
//nolint:gosec
return -int64(q), -int64(r), true
}
if q > math.MaxInt64 || r > math.MaxInt64 {
return 0, 0, false
}
//nolint:gosec
return int64(q), int64(r), true
}
// UnmarshalText implements the [encoding.TextUnmarshaler] interface.
// See also constructor [Parse].
//
// [encoding.TextUnmarshaler]: https://pkg.go.dev/encoding#TextUnmarshaler
func (d *Decimal) UnmarshalText(text []byte) error {
var err error
*d, err = Parse(string(text))
if err != nil {
return fmt.Errorf("unmarshaling %T: %w", d, err)
}
return nil
}
// MarshalText implements the [encoding.TextMarshaler] interface.
// See also method [Decimal.String].
//
// [encoding.TextMarshaler]: https://pkg.go.dev/encoding#TextMarshaler
func (d Decimal) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
// UnmarshalBinary implements the [encoding.BinaryUnmarshaler] interface.
// See also constructor [Parse].
//
// [encoding.BinaryUnmarshaler]: https://pkg.go.dev/encoding#BinaryUnmarshaler
func (d *Decimal) UnmarshalBinary(data []byte) error {
var err error
*d, err = Parse(string(data))
if err != nil {
return fmt.Errorf("unmarshaling %T: %w", d, err)
}
return nil
}
// MarshalBinary implements the [encoding.BinaryMarshaler] interface.
// See also method [Decimal.String].
//
// [encoding.BinaryMarshaler]: https://pkg.go.dev/encoding#BinaryMarshaler
func (d Decimal) MarshalBinary() ([]byte, error) {
return []byte(d.String()), nil
}
// Scan implements the [sql.Scanner] interface.
// See also constructor [Parse].
//
// [sql.Scanner]: https://pkg.go.dev/database/sql#Scanner
func (d *Decimal) Scan(value any) error {
var err error
switch value := value.(type) {
case string:
*d, err = Parse(value)
case []byte:
*d, err = Parse(string(value))
case int64:
*d, err = New(value, 0)
case float64:
*d, err = NewFromFloat64(value)
case nil:
err = fmt.Errorf("converting to %T: nil is not supported", d)
default:
err = fmt.Errorf("converting from %T to %T: type %T is not supported", value, d, value)
}
return err
}
// Value implements the [driver.Valuer] interface.
// See also method [Decimal.String].
//
// [driver.Valuer]: https://pkg.go.dev/database/sql/driver#Valuer
func (d Decimal) Value() (driver.Value, error) {
return d.String(), nil
}
// Format implements the [fmt.Formatter] interface.
// The following [format verbs] are available:
//
// | Verb | Example | Description |
// | ---------- | ------- | -------------- |
// | %f, %s, %v | 5.67 | Decimal |
// | %q | "5.67" | Quoted decimal |
// | %k | 567% | Percentage |
//
// The following format flags can be used with all verbs: '+', ' ', '0', '-'.
//
// Precision is only supported for %f and %k verbs.
// For %f verb, the default precision is equal to the actual scale of the decimal,
// whereas, for verb %k the default precision is the actual scale of the decimal minus 2.
//
// [format verbs]: https://pkg.go.dev/fmt#hdr-Printing
// [fmt.Formatter]: https://pkg.go.dev/fmt#Formatter
//
//nolint:gocyclo
func (d Decimal) Format(state fmt.State, verb rune) {
var err error
// Percentage multiplier
if verb == 'k' || verb == 'K' {
d, err = d.Mul(Hundred)
if err != nil {
// This panic is handled inside the fmt package.
panic(fmt.Errorf("formatting percent: %w", err))
}
}
// Rescaling
var tzeros int
if verb == 'f' || verb == 'F' || verb == 'k' || verb == 'K' {
var scale int
switch p, ok := state.Precision(); {
case ok:
scale = p
case verb == 'k' || verb == 'K':
scale = d.Scale() - 2
case verb == 'f' || verb == 'F':
scale = d.Scale()
}
scale = max(scale, MinScale)
switch {
case scale < d.Scale():
d = d.Round(scale)
case scale > d.Scale():
tzeros = scale - d.Scale()
}
}
// Integer and fractional digits
var intdigs int
fracdigs := d.Scale()
if dprec := d.Prec(); dprec > fracdigs {
intdigs = dprec - fracdigs
}
if d.WithinOne() {
intdigs++ // leading 0
}
// Decimal point
var dpoint int
if fracdigs > 0 || tzeros > 0 {
dpoint = 1
}
// Arithmetic sign
var rsign int
if d.IsNeg() || state.Flag('+') || state.Flag(' ') {
rsign = 1
}
// Percentage sign
var psign int
if verb == 'k' || verb == 'K' {
psign = 1
}
// Openning and closing quotes
var lquote, tquote int
if verb == 'q' || verb == 'Q' {
lquote, tquote = 1, 1
}
// Calculating padding
width := lquote + rsign + intdigs + dpoint + fracdigs + tzeros + psign + tquote
var lspaces, tspaces, lzeros int
if w, ok := state.Width(); ok && w > width {
switch {
case state.Flag('-'):
tspaces = w - width
case state.Flag('0'):
lzeros = w - width
default:
lspaces = w - width
}
width = w
}
buf := make([]byte, width)
pos := width - 1
// Trailing spaces
for range tspaces {
buf[pos] = ' '
pos--
}
// Closing quote
for range tquote {
buf[pos] = '"'
pos--
}
// Percentage sign
for range psign {
buf[pos] = '%'
pos--
}
// Trailing zeros
for range tzeros {
buf[pos] = '0'
pos--
}
// Fractional digits
dcoef := d.Coef()
for range fracdigs {
buf[pos] = byte(dcoef%10) + '0'
pos--
dcoef /= 10
}
// Decimal point
for range dpoint {
buf[pos] = '.'
pos--
}
// Integer digits
for range intdigs {
buf[pos] = byte(dcoef%10) + '0'
pos--
dcoef /= 10
}
// Leading zeros
for range lzeros {
buf[pos] = '0'
pos--
}
// Arithmetic sign
for range rsign {
if d.IsNeg() {
buf[pos] = '-'
} else if state.Flag(' ') {
buf[pos] = ' '
} else {
buf[pos] = '+'
}
pos--
}
// Opening quote
for range lquote {
buf[pos] = '"'
pos--
}
// Leading spaces
for range lspaces {
buf[pos] = ' '
pos--
}
// Writing result
//nolint:errcheck
switch verb {
case 'q', 'Q', 's', 'S', 'v', 'V', 'f', 'F', 'k', 'K':
state.Write(buf)
default:
state.Write([]byte("%!"))
state.Write([]byte{byte(verb)})
state.Write([]byte("(decimal.Decimal="))
state.Write(buf)
state.Write([]byte(")"))
}
}
// Prec returns the number of digits in the coefficient.
// See also method [Decimal.Coef].
func (d Decimal) Prec() int {
return d.coef.prec()
}
// Coef returns the coefficient of the decimal.
// See also method [Decimal.Prec].
func (d Decimal) Coef() uint64 {
return uint64(d.coef)
}
// Scale returns the number of digits after the decimal point.
// See also methods [Decimal.Prec], [Decimal.MinScale].
func (d Decimal) Scale() int {
return int(d.scale)
}
// MinScale returns the smallest scale that the decimal can be rescaled to
// without rounding.
// See also method [Decimal.Trim].
func (d Decimal) MinScale() int {
// Special case: zero
if d.IsZero() {
return MinScale
}
// General case
dcoef := d.coef
return max(MinScale, d.Scale()-dcoef.ntz())
}
// IsInt returns true if there are no significant digits after the decimal point.
func (d Decimal) IsInt() bool {
return d.coef%pow10[d.Scale()] == 0
}
// IsOne returns:
//
// true if d = -1 or d = 1
// false otherwise
func (d Decimal) IsOne() bool {
return d.coef == pow10[d.Scale()]
}
// WithinOne returns:
//
// true if -1 < d < 1
// false otherwise
func (d Decimal) WithinOne() bool {
return d.coef < pow10[d.Scale()]
}
// Round returns a decimal rounded to the specified number of digits after
// the decimal point using [rounding half to even] (banker's rounding).
// If the given scale is negative, it is redefined to zero.
// For financial calculations, the scale should be equal to or greater than
// the scale of the currency.
// See also method [Decimal.Rescale].
//
// [rounding half to even]: https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even
func (d Decimal) Round(scale int) Decimal {
scale = max(scale, MinScale)
if scale >= d.Scale() {
return d
}
coef := d.coef
coef = coef.rshHalfEven(d.Scale() - scale)
return newUnsafe(d.IsNeg(), coef, scale)
}
// Pad returns a decimal zero-padded to the specified number of digits after
// the decimal point.
// The total number of digits in the result is limited by [MaxPrec].
// See also method [Decimal.Trim].
func (d Decimal) Pad(scale int) Decimal {
scale = min(scale, MaxScale, MaxPrec-d.Prec()+d.Scale())
if scale <= d.Scale() {
return d
}
coef := d.coef
coef, ok := coef.lsh(scale - d.Scale())
if !ok {
return d // Should never happen
}
return newUnsafe(d.IsNeg(), coef, scale)
}
// Rescale returns a decimal rounded or zero-padded to the given number of digits
// after the decimal point.
// If the given scale is negative, it is redefined to zero.
// For financial calculations, the scale should be equal to or greater than
// the scale of the currency.
// See also methods [Decimal.Round], [Decimal.Pad].
func (d Decimal) Rescale(scale int) Decimal {
if scale > d.Scale() {
return d.Pad(scale)
}
return d.Round(scale)
}
// Quantize returns a decimal rescaled to the same scale as decimal e.
// The sign and the coefficient of decimal e are ignored.
// See also methods [Decimal.SameScale] and [Decimal.Rescale].
func (d Decimal) Quantize(e Decimal) Decimal {
return d.Rescale(e.Scale())
}
// SameScale returns true if decimals have the same scale.
// See also methods [Decimal.Scale], [Decimal.Quantize].
func (d Decimal) SameScale(e Decimal) bool {
return d.Scale() == e.Scale()
}
// Trunc returns a decimal truncated to the specified number of digits
// after the decimal point using [rounding toward zero].
// If the given scale is negative, it is redefined to zero.
// For financial calculations, the scale should be equal to or greater than
// the scale of the currency.
//
// [rounding toward zero]: https://en.wikipedia.org/wiki/Rounding#Rounding_toward_zero
func (d Decimal) Trunc(scale int) Decimal {
scale = max(scale, MinScale)
if scale >= d.Scale() {
return d
}
coef := d.coef
coef = coef.rshDown(d.Scale() - scale)
return newUnsafe(d.IsNeg(), coef, scale)
}
// Trim returns a decimal with trailing zeros removed up to the given number of
// digits after the decimal point.
// If the given scale is negative, it is redefined to zero.
// See also method [Decimal.Pad].
func (d Decimal) Trim(scale int) Decimal {