|
export const calculateRawAmount = (amount: number, decimals: number): bigint => { |
|
const [integerPart, fractionalPart = ''] = amount.toString().split('.'); |
|
|
|
// Ensure the fractional part has enough digits |
|
const paddedFraction = fractionalPart.padEnd(decimals, '0').slice(0, decimals); |
|
|
|
return BigInt(integerPart + paddedFraction); |
|
}; |
This code convets number to a string and then slices the string by the dot. Works well for regular numbers, but not for very small ones, for example 0.000000001 convers by js to 1e-9.
The easiest and most reliable way to convert any number in any notation is by Intl.NumberFormat:
Intl.NumberFormat('en-US', { maximumFractionDigits: decimals || 36 }).format(Number(value)) will return string of value (with e-notation or not) without loss in precision, but it may be slower than finding index of e and then converting via slicing and concatenating. In any case, e-notation should be handled if developer prefers amount over rawAmount for ton assets.
tac-sdk/src/sdk/Utils.ts
Lines 114 to 121 in c2453bc
This code convets number to a string and then slices the string by the dot. Works well for regular numbers, but not for very small ones, for example
0.000000001convers by js to1e-9.The easiest and most reliable way to convert any number in any notation is by
Intl.NumberFormat:Intl.NumberFormat('en-US', { maximumFractionDigits: decimals || 36 }).format(Number(value))will return string ofvalue(with e-notation or not) without loss in precision, but it may be slower than finding index ofeand then converting via slicing and concatenating. In any case, e-notation should be handled if developer prefersamountoverrawAmountfor ton assets.