@@ -10,8 +10,9 @@ function countDecimals(value: number): number {
10
10
11
11
// Handle scientific notation
12
12
if ( str . includes ( 'e-' ) ) {
13
- const [ , exp ] = str . split ( 'e-' ) ;
14
- return Number ( exp ) ;
13
+ const [ nonExp , exp ] = str . split ( 'e-' ) ;
14
+ const [ , decimals ] = nonExp . split ( '.' ) ;
15
+ return Number ( exp ) + decimals . length ;
15
16
}
16
17
return str . split ( '.' ) [ 1 ] ?. length || 0 ;
17
18
}
@@ -31,11 +32,11 @@ export function convertToUsd(
31
32
const rateDecimals = countDecimals ( rate ) ;
32
33
const targetPrecision = getTargetPrecision ( rateDecimals , decimals ) ;
33
34
34
- // Convert the rate to a fixed-point integer (truncated to avoid rounding errors) .
35
- // If the amount has more decimals than the rate, we need to add zeros to the rate.
36
- // If not, we don't need to do anything.
37
- const ratePrecision = 10 ** targetPrecision ;
38
- const rateFixed = Math . trunc ( rate * ratePrecision ) ;
35
+ // Get how many decimal places we need to apply to the rate to match the amount precision .
36
+ // Usually the amount has more decimals than the rate, so we need to add zeros to the rate.
37
+ const ratePrecision = Math . max ( decimals - rateDecimals , 0 ) ;
38
+ const rateUnits = bn . parseUnits ( rate . toFixed ( rateDecimals ) , rateDecimals ) ;
39
+ const rateFixed = rateUnits . mul ( bn ( 10 ) . pow ( ratePrecision ) ) ;
39
40
40
41
// Get how many decimal places we need to apply to the amount to match the rate precision.
41
42
// Sometimes the rate has more decimals than the amount, so we need to add zeros to the amount.
0 commit comments