So I’m doing some pondering with ICP tokens and their amounts are returned from candid as BigInt with an arbitrary precision defined as number of Decimals

I’m wondering what is the most common practice to handle this in JS/TS? I tried using decimal.js with some glue but it seems ugly and looks like I’m missing something super obvious

I’m interested in not just displaying this in a readable format but need to do some basic math… I could obviously do this right with the underlying BigInts but I do have a mix of regular natural/floating point numbers and BigInts so it’s error-prone kind of

What are you using guys?

Hey for that my suggestion would be to use Bignumber library.

if you try to achieve this without bignumber library, in some cases you will face some inaccuracy in calculations since you’re working with floating points.

**Installing bignumber**

```
npm i bignumber.js
```

**Example**

here is a simple function to convert raw number without decimals to a number with decimals

```
function applyDecimals(rawNumber,decimals){
return new BigNumber(rawNumber)
.dividedBy(10 ** decimals)
.toString();
}
```

this returns the number in a string format but if you want it in a number format use .toNumber()z instead of .toString().

generally try to use bignumber for your math operations since it prevents all the inaccuracies and problems in calculations.

1 Like

I see that BigNumber has only a global config for decimal places, it’s a bit confusing…

I want to be able to handle mixed numbers(each having an arbitrary number of decimal places as specified in icrc-1 standard), do I have to handle this manually when converting down to BigInt?

Oh I see now…

quote from their docs:

If a base is specified, `n`

is rounded according to the current `DECIMAL_PLACES`

and `ROUNDING_MODE`

settings. *This includes base *`10`

so don’t include a `base`

parameter for decimal values unless this behaviour is wanted.

so basically it’s an arbitrary precision inside the lib, unless you want otherwise. Nice

1 Like

true bignumber in the beginning is not really clear but once you start working with it, you will love it.

you can handle any number with any decimal places with the function i sent you, it has a parameter for decimal places so it will calculate based on what you provide as decimals.

function applyDecimals(rawNumber,decimals){

1 Like