-
Notifications
You must be signed in to change notification settings - Fork 1
/
format_uint256.go
78 lines (66 loc) · 1.6 KB
/
format_uint256.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
package decimal
import (
"strings"
"github.com/holiman/uint256"
)
// todo: faster uint256 format
func FormatUint256(number *uint256.Int, mantissa int) string {
if number == nil {
return "0"
}
if number.IsZero() {
return "0"
}
stringNumber := number.ToBig().String()
if mantissa == 0 {
return stringNumber
}
if stringNumber == "" {
return "0"
}
decimalsDiff := len(stringNumber) - mantissa
if decimalsDiff > 0 {
var str strings.Builder
str.Grow(len(stringNumber) + 1)
str.WriteString(stringNumber[0:decimalsDiff])
zerosStart := len(stringNumber) - 1
for zerosStart > decimalsDiff-1 && stringNumber[zerosStart] == '0' {
zerosStart--
}
if zerosStart > decimalsDiff-1 {
str.WriteString(".")
str.WriteString(stringNumber[decimalsDiff : zerosStart+1])
}
return str.String()
}
if decimalsDiff < 0 {
var zerosCount = mantissa - len(stringNumber)
var str strings.Builder
str.Grow(len(stringNumber) + 2 + zerosCount)
str.WriteString("0.")
for i := 0; i < zerosCount; i++ {
str.WriteString("0")
}
zerosStart := len(stringNumber) - 1
for zerosStart >= 0 && stringNumber[zerosStart] == '0' {
zerosStart--
}
if zerosStart > -1 {
str.WriteString(stringNumber[:zerosStart+1])
}
//str.WriteString(stringNumber[:zerosStart+])
return str.String()
}
var str strings.Builder
str.Grow(len(stringNumber) + 2)
str.WriteString("0")
zerosStart := len(stringNumber) - 1
for stringNumber[zerosStart] == '0' && zerosStart >= 0 {
zerosStart--
}
if zerosStart > -1 {
str.WriteString(".")
str.WriteString(stringNumber[:zerosStart+1])
}
return str.String()
}