-
Notifications
You must be signed in to change notification settings - Fork 693
Expand file tree
/
Copy pathdecimal.go
More file actions
1303 lines (1090 loc) · 34.9 KB
/
decimal.go
File metadata and controls
1303 lines (1090 loc) · 34.9 KB
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 osmomath
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"testing"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// NOTE: never use new(BigDec) or else we will panic unmarshalling into the
// nil embedded big.Int
type BigDec struct {
i *big.Int
}
const (
// number of decimal places
BigDecPrecision = 36
// bytes required to represent the above precision
// Ceiling[Log2[10**Precision - 1]]
BigDecimalPrecisionBits = 120
maxDecBitLen = maxBitLen + BigDecimalPrecisionBits
// max number of iterations in ApproxRoot function
maxApproxRootIterations = 100
// max number of iterations in Log2 function
maxLog2Iterations = 300
)
var (
defaultBigDecPrecisionReuse = new(big.Int).Exp(big.NewInt(10), big.NewInt(BigDecPrecision), nil)
precisionReuseSDKDec = new(big.Int).Exp(big.NewInt(10), big.NewInt(DecPrecision), nil)
bigDecDecPrecision = new(big.Int).Mul(defaultBigDecPrecisionReuse, precisionReuseSDKDec)
squaredPrecisionReuse = new(big.Int).Mul(defaultBigDecPrecisionReuse, defaultBigDecPrecisionReuse)
bigDecDecPrecisionFactorDiff = new(big.Int).Exp(big.NewInt(10), big.NewInt(BigDecPrecision-DecPrecision), nil)
fivePrecision = new(big.Int).Quo(defaultBigDecPrecisionReuse, big.NewInt(2))
fivePrecisionSDKDec = new(big.Int).Quo(precisionReuseSDKDec, big.NewInt(2))
precisionMultipliers []*big.Int
zeroInt = big.NewInt(0)
oneInt = big.NewInt(1)
tenInt = big.NewInt(10)
// log_2(e)
// From: https://www.wolframalpha.com/input?i=log_2%28e%29+with+37+digits
logOfEbase2 = MustNewBigDecFromStr("1.442695040888963407359924681001892137")
// log_2(1.0001)
// From: https://www.wolframalpha.com/input?i=log_2%281.0001%29+to+33+digits
tickLogOf2 = MustNewBigDecFromStr("0.000144262291094554178391070900057480")
// initialized in init() since requires
// precision to be defined.
twoBigDec BigDec = MustNewBigDecFromStr("2")
// precisionFactors are used to adjust the scale of big.Int values to match the desired precision
precisionFactors = make(map[uint64]*big.Int)
zeroBigDec BigDec = ZeroBigDec()
oneBigDec BigDec = OneBigDec()
oneHalfBigDec BigDec = oneBigDec.Quo(twoBigDec)
negOneBigDec BigDec = oneBigDec.Neg()
)
// Decimal errors
var (
ErrEmptyDecimalStr = errors.New("decimal string cannot be empty")
ErrInvalidDecimalLength = errors.New("invalid decimal length")
ErrInvalidDecimalStr = errors.New("invalid decimal string")
)
// Set precision multipliers
func init() {
precisionMultipliers = make([]*big.Int, BigDecPrecision+1)
for i := 0; i <= BigDecPrecision; i++ {
precisionMultipliers[i] = calcPrecisionMultiplier(int64(i))
}
for precision := uint64(0); precision <= BigDecPrecision; precision++ {
precisionFactor := new(big.Int).Exp(big.NewInt(10), big.NewInt(BigDecPrecision-int64(precision)), nil)
precisionFactors[precision] = precisionFactor
}
}
func precisionInt() *big.Int {
return new(big.Int).Set(defaultBigDecPrecisionReuse)
}
func ZeroBigDec() BigDec { return BigDec{new(big.Int).Set(zeroInt)} }
func OneBigDec() BigDec { return BigDec{precisionInt()} }
func SmallestBigDec() BigDec { return BigDec{new(big.Int).Set(oneInt)} }
// calculate the precision multiplier
func calcPrecisionMultiplier(prec int64) *big.Int {
if prec > BigDecPrecision {
panic(fmt.Sprintf("too much precision, maximum %v, provided %v", BigDecPrecision, prec))
}
zerosToAdd := BigDecPrecision - prec
multiplier := new(big.Int).Exp(tenInt, big.NewInt(zerosToAdd), nil)
return multiplier
}
// get the precision multiplier, do not mutate result
func precisionMultiplier(prec int64) *big.Int {
if prec > BigDecPrecision {
panic(fmt.Sprintf("too much precision, maximum %v, provided %v", BigDecPrecision, prec))
}
return precisionMultipliers[prec]
}
// create a new NewBigDec from integer assuming whole number
func NewBigDec(i int64) BigDec {
return NewBigDecWithPrec(i, 0)
}
// create a new BigDec from integer with decimal place at prec
// CONTRACT: prec <= BigDecPrecision
func NewBigDecWithPrec(i, prec int64) BigDec {
bi := big.NewInt(i)
return BigDec{
bi.Mul(bi, precisionMultiplier(prec)),
}
}
// create a new BigDec from big integer assuming whole numbers
// CONTRACT: prec <= BigDecPrecision
func NewBigDecFromBigInt(i *big.Int) BigDec {
return NewBigDecFromBigIntWithPrec(i, 0)
}
func NewBigDecFromBigIntMut(i *big.Int) BigDec {
return NewBigDecFromBigIntMutWithPrec(i, 0)
}
// create a new BigDec from big integer assuming whole numbers
// CONTRACT: prec <= BigDecPrecision
func NewBigDecFromBigIntWithPrec(i *big.Int, prec int64) BigDec {
return BigDec{
new(big.Int).Mul(i, precisionMultiplier(prec)),
}
}
// returns a BigDec, built using a mutated copy of the passed in bigint.
// CONTRACT: prec <= BigDecPrecision
func NewBigDecFromBigIntMutWithPrec(i *big.Int, prec int64) BigDec {
return BigDec{
i.Mul(i, precisionMultiplier(prec)),
}
}
// create a new BigDec from big integer assuming whole numbers
// CONTRACT: prec <= BigDecPrecision
func NewBigDecFromInt(i BigInt) BigDec {
return NewBigDecFromIntWithPrec(i, 0)
}
// create a new BigDec from big integer with decimal place at prec
// CONTRACT: prec <= BigDecPrecision
func NewBigDecFromIntWithPrec(i BigInt, prec int64) BigDec {
return BigDec{
new(big.Int).Mul(i.BigInt(), precisionMultiplier(prec)),
}
}
// create a decimal from an input decimal string.
// valid must come in the form:
//
// (-) whole integers (.) decimal integers
//
// examples of acceptable input include:
//
// -123.456
// 456.7890
// 345
// -456789
//
// NOTE - An error will return if more decimal places
// are provided in the string than the constant Precision.
//
// CONTRACT - This function does not mutate the input str.
func NewBigDecFromStr(str string) (BigDec, error) {
if len(str) == 0 {
return BigDec{}, ErrEmptyDecimalStr
}
// first extract any negative symbol
neg := false
if str[0] == '-' {
neg = true
str = str[1:]
}
if len(str) == 0 {
return BigDec{}, ErrEmptyDecimalStr
}
strs := strings.Split(str, ".")
lenDecs := 0
combinedStr := strs[0]
if len(strs) == 2 { // has a decimal place
lenDecs = len(strs[1])
if lenDecs == 0 || len(combinedStr) == 0 {
return BigDec{}, ErrInvalidDecimalLength
}
combinedStr += strs[1]
} else if len(strs) > 2 {
return BigDec{}, ErrInvalidDecimalStr
}
if lenDecs > BigDecPrecision {
return BigDec{}, fmt.Errorf("invalid precision; max: %d, got: %d", BigDecPrecision, lenDecs)
}
// add some extra zero's to correct to the Precision factor
zerosToAdd := BigDecPrecision - lenDecs
zeros := fmt.Sprintf(`%0`+strconv.Itoa(zerosToAdd)+`s`, "")
combinedStr += zeros
combined, ok := new(big.Int).SetString(combinedStr, 10) // base 10
if !ok {
return BigDec{}, fmt.Errorf("failed to set decimal string: %s", combinedStr)
}
if combined.BitLen() > maxBitLen {
return BigDec{}, fmt.Errorf("decimal out of range; bitLen: got %d, max %d", combined.BitLen(), maxBitLen)
}
if neg {
combined = new(big.Int).Neg(combined)
}
return BigDec{combined}, nil
}
// Decimal from string, panic on error
func MustNewBigDecFromStr(s string) BigDec {
dec, err := NewBigDecFromStr(s)
if err != nil {
panic(err)
}
return dec
}
func (d BigDec) IsNil() bool { return d.i == nil } // is decimal nil
func (d BigDec) IsZero() bool { return (d.i).Sign() == 0 } // is equal to zero
func (d BigDec) IsNegative() bool { return (d.i).Sign() == -1 } // is negative
func (d BigDec) IsPositive() bool { return (d.i).Sign() == 1 } // is positive
func (d BigDec) Equal(d2 BigDec) bool { return (d.i).Cmp(d2.i) == 0 } // equal decimals
func (d BigDec) GT(d2 BigDec) bool { return (d.i).Cmp(d2.i) > 0 } // greater than
func (d BigDec) GTE(d2 BigDec) bool { return (d.i).Cmp(d2.i) >= 0 } // greater than or equal
func (d BigDec) LT(d2 BigDec) bool { return (d.i).Cmp(d2.i) < 0 } // less than
func (d BigDec) LTE(d2 BigDec) bool { return (d.i).Cmp(d2.i) <= 0 } // less than or equal
func (d BigDec) Neg() BigDec { return BigDec{new(big.Int).Neg(d.i)} } // reverse the decimal sign
// nolint: stylecheck
func (d BigDec) Abs() BigDec { return BigDec{new(big.Int).Abs(d.i)} } // absolute value
func (d BigDec) AbsMut() BigDec { d.i.Abs(d.i); return d } // absolute value
// BigInt returns a copy of the underlying big.Int.
func (d BigDec) BigInt() *big.Int {
if d.IsNil() {
return nil
}
cp := new(big.Int)
return cp.Set(d.i)
}
// BigIntMut returns the pointer of the underlying big.Int.
func (d BigDec) BigIntMut() *big.Int {
if d.IsNil() {
return nil
}
return d.i
}
// addition
func (d BigDec) Add(d2 BigDec) BigDec {
copy := d.Clone()
copy.AddMut(d2)
return copy
}
// mutative addition
func (d BigDec) AddMut(d2 BigDec) BigDec {
d.i.Add(d.i, d2.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// subtraction
func (d BigDec) Sub(d2 BigDec) BigDec {
copy := d.Clone()
copy.SubMut(d2)
return copy
}
func (d BigDec) SubMut(d2 BigDec) BigDec {
res := d.i.Sub(d.i, d2.i)
if res.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{res}
}
func (d BigDec) NegMut() BigDec {
d.i.Neg(d.i)
return d
} // reverse the decimal sign
// Clone performs a deep copy of the receiver
// and returns the new result.
func (d BigDec) Clone() BigDec {
copy := BigDec{new(big.Int)}
copy.i.Set(d.i)
return copy
}
// Mut performs non-mutative multiplication.
// The receiver is not modifier but the result is.
func (d BigDec) Mul(d2 BigDec) BigDec {
copy := d.Clone()
copy.MulMut(d2)
return copy
}
// Mut performs non-mutative multiplication.
// The receiver is not modifier but the result is.
func (d BigDec) MulMut(d2 BigDec) BigDec {
d.i.Mul(d.i, d2.i)
d.i = chopPrecisionAndRound(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{d.i}
}
func (d BigDec) MulDec(d2 Dec) BigDec {
copy := d.Clone()
copy.MulDecMut(d2)
return copy
}
func (d BigDec) MulDecMut(d2 Dec) BigDec {
d.i.Mul(d.i, d2.BigIntMut())
d.i = chopPrecisionAndRoundSdkDec(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{d.i}
}
// multiplication truncate
func (d BigDec) MulTruncate(d2 BigDec) BigDec {
mul := new(big.Int).Mul(d.i, d2.i)
chopped := chopPrecisionAndTruncateMut(mul, defaultBigDecPrecisionReuse)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{chopped}
}
func (d BigDec) MulTruncateDec(d2 Dec) BigDec {
mul := new(big.Int).Mul(d.i, d2.BigIntMut())
chopped := chopPrecisionAndTruncateMut(mul, precisionReuseSDKDec)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{chopped}
}
// multiplication round up
func (d BigDec) MulRoundUp(d2 BigDec) BigDec {
mul := new(big.Int).Mul(d.i, d2.i)
chopped := chopPrecisionAndRoundUpMut(mul, defaultBigDecPrecisionReuse)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{chopped}
}
// multiplication
func (d BigDec) MulInt(i BigInt) BigDec {
mul := new(big.Int).Mul(d.i, i.i)
if mul.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{mul}
}
// MulInt64 - multiplication with int64
func (d BigDec) MulInt64(i int64) BigDec {
bi := big.NewInt(i)
mul := bi.Mul(d.i, bi)
if mul.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{mul}
}
// quotient
func (d BigDec) Quo(d2 BigDec) BigDec {
copy := d.Clone()
copy.QuoMut(d2)
return copy
}
// mutative quotient
func (d BigDec) QuoMut(d2 BigDec) BigDec {
// multiply precision twice
d.i.Mul(d.i, squaredPrecisionReuse)
d.i.Quo(d.i, d2.i)
chopPrecisionAndRound(d.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
func (d BigDec) QuoRaw(d2 int64) BigDec {
// multiply precision, so we can chop it later
mul := new(big.Int).Mul(d.i, defaultBigDecPrecisionReuse)
quo := mul.Quo(mul, big.NewInt(d2))
chopped := chopPrecisionAndRound(quo)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{chopped}
}
// quotient truncate
func (d BigDec) QuoTruncate(d2 BigDec) BigDec {
// multiply precision twice
mul := new(big.Int).Mul(d.i, defaultBigDecPrecisionReuse)
quo := mul.Quo(mul, d2.i)
if quo.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{quo}
}
// quotient truncate (mutative)
func (d BigDec) QuoTruncateMut(d2 BigDec) BigDec {
// multiply bigDec precision
d.i.Mul(d.i, defaultBigDecPrecisionReuse)
d.i.Quo(d.i, d2.i)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// quotient truncate
func (d BigDec) QuoTruncateDec(d2 Dec) BigDec {
// multiply Dec Precision
mul := new(big.Int).Mul(d.i, precisionReuseSDKDec)
quo := mul.Quo(mul, d2.BigIntMut())
if quo.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{quo}
}
// quotient truncate (mutative)
func (d BigDec) QuoTruncateDecMut(d2 Dec) BigDec {
// multiply Dec Precision
d.i.Mul(d.i, precisionReuseSDKDec)
d.i.Quo(d.i, d2.BigIntMut())
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return d
}
// quotient, round up
func (d BigDec) QuoRoundUp(d2 BigDec) BigDec {
// multiply precision twice
mul := new(big.Int).Mul(d.i, squaredPrecisionReuse)
quo := mul.Quo(mul, d2.i)
chopped := chopPrecisionAndRoundUpMut(quo, defaultBigDecPrecisionReuse)
if chopped.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{chopped}
}
// quotient, round up (mutative)
func (d BigDec) QuoRoundUpMut(d2 BigDec) BigDec {
// multiply precision twice
d.i.Mul(d.i, squaredPrecisionReuse)
d.i.Quo(d.i, d2.i)
chopPrecisionAndRoundUpMut(d.i, defaultBigDecPrecisionReuse)
if d.i.BitLen() > maxDecBitLen {
panic("Int overflow")
}
return BigDec{d.i}
}
// quotient
func (d BigDec) QuoInt(i BigInt) BigDec {
mul := new(big.Int).Quo(d.i, i.i)
return BigDec{mul}
}
// QuoInt64 - quotient with int64
func (d BigDec) QuoInt64(i int64) BigDec {
mul := new(big.Int).Quo(d.i, big.NewInt(i))
return BigDec{mul}
}
// ApproxRoot returns an approximate estimation of a Dec's positive real nth root
// using Newton's method (where n is positive). The algorithm starts with some guess and
// computes the sequence of improved guesses until an answer converges to an
// approximate answer. It returns `|d|.ApproxRoot() * -1` if input is negative.
// A maximum number of 100 iterations is used a backup boundary condition for
// cases where the answer never converges enough to satisfy the main condition.
func (d BigDec) ApproxRoot(root uint64) (guess BigDec, err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = errors.New("out of bounds")
}
}
}()
if d.IsNegative() {
absRoot, err := d.MulInt64(-1).ApproxRoot(root)
return absRoot.MulInt64(-1), err
}
if root == 1 || d.IsZero() || d.Equal(oneBigDec) {
return d, nil
}
if root == 0 {
return OneBigDec(), nil
}
rootInt := NewBigIntFromUint64(root)
guess, delta := OneBigDec(), OneBigDec()
for iter := 0; delta.Abs().GT(SmallestBigDec()) && iter < maxApproxRootIterations; iter++ {
prev := guess.PowerInteger(root - 1)
if prev.IsZero() {
prev = SmallestBigDec()
}
delta = d.Quo(prev)
delta.SubMut(guess)
delta = delta.QuoInt(rootInt)
guess = guess.Add(delta)
}
return guess, nil
}
// ApproxSqrt is a wrapper around ApproxRoot for the common special case
// of finding the square root of a number. It returns -(sqrt(abs(d)) if input is negative.
// TODO: Optimize this to be faster just using native big int sqrt.
func (d BigDec) ApproxSqrt() (BigDec, error) {
return d.ApproxRoot(2)
}
// is integer, e.g. decimals are zero
func (d BigDec) IsInteger() bool {
return new(big.Int).Rem(d.i, defaultBigDecPrecisionReuse).Sign() == 0
}
// format decimal state
func (d BigDec) Format(s fmt.State, verb rune) {
_, err := s.Write([]byte(d.String()))
if err != nil {
panic(err)
}
}
// String returns a BigDec as a string.
func (d BigDec) String() string {
if d.i == nil {
return d.i.String()
}
isNeg := d.IsNegative()
if isNeg {
d = d.Neg()
}
bzInt, err := d.i.MarshalText()
if err != nil {
return ""
}
inputSize := len(bzInt)
var bzStr []byte
// TODO: Remove trailing zeros
// case 1, purely decimal
if inputSize <= BigDecPrecision {
bzStr = make([]byte, BigDecPrecision+2)
// 0. prefix
bzStr[0] = byte('0')
bzStr[1] = byte('.')
// set relevant digits to 0
for i := 0; i < BigDecPrecision-inputSize; i++ {
bzStr[i+2] = byte('0')
}
// set final digits
copy(bzStr[2+(BigDecPrecision-inputSize):], bzInt)
} else {
// inputSize + 1 to account for the decimal point that is being added
bzStr = make([]byte, inputSize+1)
decPointPlace := inputSize - BigDecPrecision
copy(bzStr, bzInt[:decPointPlace]) // pre-decimal digits
bzStr[decPointPlace] = byte('.') // decimal point
copy(bzStr[decPointPlace+1:], bzInt[decPointPlace:]) // post-decimal digits
}
if isNeg {
return "-" + string(bzStr)
}
return string(bzStr)
}
// Float64 returns the float64 representation of a BigDec.
// Will return the error if the conversion failed.
func (d BigDec) Float64() (float64, error) {
return strconv.ParseFloat(d.String(), 64)
}
// MustFloat64 returns the float64 representation of a BigDec.
// Would panic if the conversion failed.
func (d BigDec) MustFloat64() float64 {
if value, err := strconv.ParseFloat(d.String(), 64); err != nil {
panic(err)
} else {
return value
}
}
// Dec returns the osmomath.Dec representation of a BigDec.
// Values in any additional decimal places are truncated.
func (d BigDec) Dec() Dec {
dec := math.LegacyNewDec(0)
decBi := dec.BigIntMut()
decBi.Quo(d.i, bigDecDecPrecisionFactorDiff)
return dec
}
// DecWithPrecision converts BigDec to Dec with desired precision
// Example:
// BigDec: 1.010100000000153000000000000000000000
// precision: 4
// Output Dec: 1.010100000000000000
// Panics if precision exceeds DecPrecision
func (d BigDec) DecWithPrecision(precision uint64) Dec {
var precisionFactor *big.Int
if precision > DecPrecision {
panic(fmt.Sprintf("maximum Dec precision is (%v), provided (%v)", DecPrecision, precision))
} else {
precisionFactor = precisionFactors[precision]
}
// Truncate any additional decimal values that exist due to BigDec's additional precision
// This relies on big.Int's Quo function doing floor division
intRepresentation := new(big.Int).Quo(d.BigIntMut(), precisionFactor)
// convert int representation back to SDK Dec precision
truncatedDec := NewDecFromBigIntWithPrec(intRepresentation, int64(precision))
return truncatedDec
}
// ChopPrecisionMut truncates all decimals after precision numbers after decimal point. Mutative
// CONTRACT: precision <= BigDecPrecision
// Panics if precision exceeds BigDecPrecision
func (d *BigDec) ChopPrecisionMut(precision uint64) BigDec {
if precision > BigDecPrecision {
panic(fmt.Sprintf("maximum BigDec precision is (%v), provided (%v)", DecPrecision, precision))
}
precisionFactor := precisionFactors[precision]
// big.Quo truncates numbers that would have been after decimal point
d.i.Quo(d.i, precisionFactor)
d.i.Mul(d.i, precisionFactor)
return BigDec{d.i}
}
// ChopPrecision truncates all decimals after precision numbers after decimal point
// CONTRACT: precision <= BigDecPrecision
// Panics if precision exceeds BigDecPrecision
func (d *BigDec) ChopPrecision(precision uint64) BigDec {
copy := d.Clone()
return copy.ChopPrecisionMut(precision)
}
// DecRoundUp returns the osmomath.Dec representation of a BigDec.
// Round up at precision end.
// Values in any additional decimal places are truncated.
func (d BigDec) DecRoundUp() Dec {
return NewDecFromBigIntWithPrec(chopPrecisionAndRoundUpDec(d.i), DecPrecision)
}
// BigDecFromDec returns the BigDec representation of an Dec.
// Values in any additional decimal places are truncated.
func BigDecFromDec(d Dec) BigDec {
return NewBigDecFromBigIntMutWithPrec(d.BigInt(), DecPrecision)
}
// BigDecFromDec returns the BigDec representation of an Dec.
// Values in any additional decimal places are truncated.
func BigDecFromDecMut(d Dec) BigDec {
return NewBigDecFromBigIntMutWithPrec(d.BigIntMut(), DecPrecision)
}
// BigDecFromSDKInt returns the BigDec representation of an sdkInt.
// Values in any additional decimal places are truncated.
func BigDecFromSDKInt(i Int) BigDec {
return NewBigDecFromBigIntWithPrec(i.BigIntMut(), 0)
}
// BigDecFromDecSlice returns the []BigDec representation of an []Dec.
// Values in any additional decimal places are truncated.
func BigDecFromDecSlice(ds []Dec) []BigDec {
result := make([]BigDec, len(ds))
for i, d := range ds {
result[i] = NewBigDecFromBigIntMutWithPrec(d.BigInt(), DecPrecision)
}
return result
}
// BigDecFromDecSlice returns the []BigDec representation of an []Dec.
// Values in any additional decimal places are truncated.
func BigDecFromDecCoinSlice(ds []sdk.DecCoin) []BigDec {
result := make([]BigDec, len(ds))
for i, d := range ds {
result[i] = NewBigDecFromBigIntMutWithPrec(d.Amount.BigInt(), DecPrecision)
}
return result
}
// ____
// __| |__ "chop 'em
// ` \ round!"
// ___|| ~ _ -bankers
// | | __
// | | | __|__|__
// |_____: / | $$$ |
// |________|
// Remove a Precision amount of rightmost digits and perform bankers rounding
// on the remainder (gaussian rounding) on the digits which have been removed.
//
// Mutates the input. Use the non-mutative version if that is undesired
func chopPrecisionAndRound(d *big.Int) *big.Int {
// remove the negative and add it back when returning
if d.Sign() == -1 {
// make d positive, compute chopped value, and then un-mutate d
d = d.Neg(d)
d = chopPrecisionAndRound(d)
d = d.Neg(d)
return d
}
// get the truncated quotient and remainder
quo, rem := d, big.NewInt(0)
quo, rem = quo.QuoRem(d, defaultBigDecPrecisionReuse, rem)
if rem.Sign() == 0 { // remainder is zero
return quo
}
switch rem.Cmp(fivePrecision) {
case -1:
return quo
case 1:
return quo.Add(quo, oneInt)
default: // bankers rounding must take place
// always round to an even number
if quo.Bit(0) == 0 {
return quo
}
return quo.Add(quo, oneInt)
}
}
// TODO: Abstract code
func chopPrecisionAndRoundSdkDec(d *big.Int) *big.Int {
// remove the negative and add it back when returning
if d.Sign() == -1 {
// make d positive, compute chopped value, and then un-mutate d
d = d.Neg(d)
d = chopPrecisionAndRoundSdkDec(d)
d = d.Neg(d)
return d
}
// get the truncated quotient and remainder
quo, rem := d, big.NewInt(0)
quo, rem = quo.QuoRem(d, precisionReuseSDKDec, rem)
if rem.Sign() == 0 { // remainder is zero
return quo
}
switch rem.Cmp(fivePrecisionSDKDec) {
case -1:
return quo
case 1:
return quo.Add(quo, oneInt)
default: // bankers rounding must take place
// always round to an even number
if quo.Bit(0) == 0 {
return quo
}
return quo.Add(quo, oneInt)
}
}
// chopPrecisionAndRoundUpDec removes DecPrecision amount of rightmost digits and rounds up.
// Non-mutative.
func chopPrecisionAndRoundUpDec(d *big.Int) *big.Int {
copy := new(big.Int).Set(d)
return chopPrecisionAndRoundUpMut(copy, precisionReuseSDKDec)
}
// chopPrecisionAndRoundUp removes a Precision amount of rightmost digits and rounds up.
// Mutates input d.
// Mutations occur:
// - By calling chopPrecisionAndTruncateMut.
// - Using input d directly in QuoRem.
func chopPrecisionAndRoundUpMut(d *big.Int, precisionReuse *big.Int) *big.Int {
// remove the negative and add it back when returning
if d.Sign() == -1 {
// make d positive, compute chopped value, and then un-mutate d
d = d.Neg(d)
// truncate since d is negative...
d = chopPrecisionAndTruncateMut(d, precisionReuse)
d = d.Neg(d)
return d
}
// get the truncated quotient and remainder
_, rem := d.QuoRem(d, precisionReuse, big.NewInt(0))
if rem.Sign() == 0 { // remainder is zero
return d
}
return d.Add(d, oneInt)
}
func chopPrecisionAndRoundNonMutative(d *big.Int) *big.Int {
tmp := new(big.Int).Set(d)
return chopPrecisionAndRound(tmp)
}
// RoundInt64 rounds the decimal using bankers rounding
func (d BigDec) RoundInt64() int64 {
chopped := chopPrecisionAndRoundNonMutative(d.i)
if !chopped.IsInt64() {
panic("Int64() out of bound")
}
return chopped.Int64()
}
// RoundInt round the decimal using bankers rounding
func (d BigDec) RoundInt() BigInt {
return NewBigIntFromBigInt(chopPrecisionAndRoundNonMutative(d.i))
}
// chopPrecisionAndTruncate is similar to chopPrecisionAndRound,
// but always rounds down. It does not mutate the input.
func chopPrecisionAndTruncate(d *big.Int, precisionReuse *big.Int) *big.Int {
return new(big.Int).Quo(d, precisionReuse)
}
// chopPrecisionAndTruncate is similar to chopPrecisionAndRound,
// but always rounds down. It mutates the input.
func chopPrecisionAndTruncateMut(d, precisionReuse *big.Int) *big.Int {
return d.Quo(d, precisionReuse)
}
// TruncateInt64 truncates the decimals from the number and returns an int64
func (d BigDec) TruncateInt64() int64 {
chopped := chopPrecisionAndTruncate(d.i, defaultBigDecPrecisionReuse)
if !chopped.IsInt64() {
panic("Int64() out of bound")
}
return chopped.Int64()
}
// TruncateInt truncates the decimals from the number and returns an Int
func (d BigDec) TruncateInt() BigInt {
return NewBigIntFromBigInt(chopPrecisionAndTruncate(d.i, defaultBigDecPrecisionReuse))
}
// TruncateDec truncates the decimals from the number and returns a Dec
func (d BigDec) TruncateDec() BigDec {
return NewBigDecFromBigInt(chopPrecisionAndTruncate(d.i, defaultBigDecPrecisionReuse))
}
// Ceil returns the smallest integer value (as a decimal) that is greater than
// or equal to the given decimal.
func (d BigDec) Ceil() BigDec {
tmp := new(big.Int).Set(d.i)
return BigDec{i: tmp}.CeilMut()
}
func (d BigDec) CeilMut() BigDec {
quo, rem := d.i, big.NewInt(0)
quo, rem = quo.QuoRem(quo, defaultBigDecPrecisionReuse, rem)
// no need to round with a zero remainder regardless of sign
if rem.Sign() <= 0 {
return NewBigDecFromBigIntMut(quo)
}
return NewBigDecFromBigIntMut(quo.Add(quo, oneInt))
}
// MaxSortableDec is the largest Dec that can be passed into SortableDecBytes()
// Its negative form is the least Dec that can be passed in.
var MaxSortableDec = OneBigDec().Quo(SmallestBigDec())
// ValidSortableDec ensures that a Dec is within the sortable bounds,
// a BigDec can't have a precision of less than 10^-18.
// Max sortable decimal was set to the reciprocal of SmallestDec.
func ValidSortableDec(dec BigDec) bool {
return dec.Abs().LTE(MaxSortableDec)
}
// SortableDecBytes returns a byte slice representation of a Dec that can be sorted.
// Left and right pads with 0s so there are 18 digits to left and right of the decimal point.
// For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec.
func SortableDecBytes(dec BigDec) []byte {
if !ValidSortableDec(dec) {
panic("dec must be within bounds")
}
// Instead of adding an extra byte to all sortable decs in order to handle max sortable, we just
// makes its bytes be "max" which comes after all numbers in ASCIIbetical order
if dec.Equal(MaxSortableDec) {
return []byte("max")
}
// For the same reason, we make the bytes of minimum sortable dec be --, which comes before all numbers.
if dec.Equal(MaxSortableDec.Neg()) {
return []byte("--")
}
// We move the negative sign to the front of all the left padded 0s, to make negative numbers come before positive numbers
if dec.IsNegative() {
return append([]byte("-"), []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", BigDecPrecision*2+1), dec.Abs().String()))...)
}
return []byte(fmt.Sprintf(fmt.Sprintf("%%0%ds", BigDecPrecision*2+1), dec.String()))
}
// reuse nil values
var nilJSON []byte
func init() {
empty := new(big.Int)
bz, _ := empty.MarshalText()