@@ -558,21 +558,22 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
558
558
if ( ! denomination ) {
559
559
throw new InvalidUnitError ( unit ) ;
560
560
}
561
- let parsedNumber = number ;
562
- if ( typeof parsedNumber === 'number' ) {
563
- if ( parsedNumber < 1e-15 ) {
561
+ let parsedNumber : string ;
562
+ if ( typeof number === 'number' ) {
563
+ if ( number < 1e-15 ) {
564
564
console . warn ( PrecisionLossWarning )
565
565
}
566
- if ( parsedNumber > 1e+20 ) {
566
+ if ( number > 1e+20 ) {
567
567
console . warn ( PrecisionLossWarning )
568
568
569
- parsedNumber = BigInt ( parsedNumber ) ;
569
+ parsedNumber = BigInt ( number ) . toLocaleString ( 'fullwide' ) ;
570
570
} else {
571
571
// in case there is a decimal point, we need to convert it to string
572
- parsedNumber = parsedNumber . toLocaleString ( 'fullwide' , { useGrouping : false , maximumFractionDigits : 20 } )
573
- }
572
+ parsedNumber = number . toLocaleString ( 'fullwide' , { useGrouping : false , maximumFractionDigits : 20 } )
573
+ }
574
+
574
575
}
575
-
576
+
576
577
// if value is decimal e.g. 24.56 extract `integer` and `fraction` part
577
578
// to avoid `fraction` to be null use `concat` with empty string
578
579
const [ integer , fraction ] = String (
@@ -581,10 +582,17 @@ export const toWei = (number: Numbers, unit: EtherUnits): string => {
581
582
. split ( '.' )
582
583
. concat ( '' ) ;
583
584
585
+ // if the number of decimal places is over 20 we need to trim the extra decimal places before multiplying by
586
+ // the denomination to avoid returning an invalid result
587
+ let trimmedFraction = fraction
588
+ if ( fraction . length >= 20 ) {
589
+ console . warn ( PrecisionLossWarning )
590
+ trimmedFraction = fraction . substring ( 0 , 20 )
591
+ }
592
+
584
593
// join the value removing `.` from
585
594
// 24.56 -> 2456
586
-
587
- const value = BigInt ( `${ integer } ${ fraction } ` ) ;
595
+ const value = BigInt ( `${ integer } ${ trimmedFraction } ` ) ;
588
596
589
597
// multiply value with denomination
590
598
// 2456 * 1000000 -> 2456000000
0 commit comments