Skip to content

calculateRawAmount does not work with e-notation #5

@10000W

Description

@10000W

tac-sdk/src/sdk/Utils.ts

Lines 114 to 121 in c2453bc

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions