@@ -23,7 +23,7 @@ public static class Utils
23
23
{
24
24
public const string AddressZero = "0x0000000000000000000000000000000000000000" ;
25
25
public const string NativeTokenAddress = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" ;
26
- public const decimal DECIMALS_18 = 1000000000000000000 ;
26
+ public const decimal DECIMALS_18 = 1_000_000_000_000_000_000M ;
27
27
28
28
public static string [ ] ToJsonStringArray ( params object [ ] args )
29
29
{
@@ -93,10 +93,22 @@ public static long UnixTimeNowMs()
93
93
94
94
public static string ToWei ( this string eth )
95
95
{
96
- if ( ! decimal . TryParse ( eth , NumberStyles . Number , CultureInfo . InvariantCulture , out decimal ethDecimal ) )
97
- throw new ArgumentException ( "Invalid eth value." ) ;
98
- BigInteger wei = ( BigInteger ) ( ethDecimal * DECIMALS_18 ) ;
99
- return wei . ToString ( ) ;
96
+ try
97
+ {
98
+ if ( ! decimal . TryParse ( eth , NumberStyles . Number , CultureInfo . InvariantCulture , out decimal ethDecimal ) )
99
+ throw new ArgumentException ( "Invalid eth value." ) ;
100
+
101
+ BigInteger wei = ( BigInteger ) ( ethDecimal * DECIMALS_18 ) ;
102
+ return wei . ToString ( ) ;
103
+ }
104
+ catch ( OverflowException )
105
+ {
106
+ if ( ! double . TryParse ( eth , NumberStyles . Number , CultureInfo . InvariantCulture , out double ethDouble ) )
107
+ throw new ArgumentException ( "Invalid eth value." ) ;
108
+
109
+ BigInteger wei = ( BigInteger ) ( ethDouble * ( double ) DECIMALS_18 ) ;
110
+ return wei . ToString ( ) ;
111
+ }
100
112
}
101
113
102
114
public static string ToEth ( this string wei , int decimalsToDisplay = 4 , bool addCommas = true )
@@ -109,15 +121,24 @@ public static string FormatERC20(this string wei, int decimalsToDisplay = 4, int
109
121
if ( ! BigInteger . TryParse ( wei , out BigInteger weiBigInt ) )
110
122
throw new ArgumentException ( "Invalid wei value." ) ;
111
123
112
- decimal eth = ( decimal ) weiBigInt / ( decimal ) Math . Pow ( 10 , decimals ) ;
113
124
string format = addCommas ? "#,0" : "#0" ;
114
125
115
126
if ( decimalsToDisplay > 0 )
127
+ {
116
128
format += "." ;
117
- for ( int i = 0 ; i < decimalsToDisplay ; i ++ )
118
- format += "#" ;
129
+ format += new string ( '#' , decimalsToDisplay ) ;
130
+ }
119
131
120
- return eth . ToString ( format ) ;
132
+ try
133
+ {
134
+ decimal eth = ( decimal ) weiBigInt / ( decimal ) BigInteger . Pow ( 10 , decimals ) ;
135
+ return eth . ToString ( format , CultureInfo . InvariantCulture ) ;
136
+ }
137
+ catch ( OverflowException )
138
+ {
139
+ double eth = ( double ) weiBigInt / Math . Pow ( 10 , decimals ) ;
140
+ return eth . ToString ( format , CultureInfo . InvariantCulture ) ;
141
+ }
121
142
}
122
143
123
144
public static BigInteger AdjustDecimals ( this BigInteger value , int fromDecimals , int toDecimals )
0 commit comments