Skip to content

Commit

Permalink
docs: add example usage for DenominatedNumber
Browse files Browse the repository at this point in the history
  • Loading branch information
tien committed Jun 14, 2024
1 parent 2924b25 commit 9502eee
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions apps/docs/docs/getting-started/number-utility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
sidebar_position: 5
---

# Number utility

To handle complexity around [planck unit](https://wiki.polkadot.network/docs/learn-DOT#the-planck-unit) used in Polkadot, a utility class [`DenominatedNumber`](/api/utils/class/DenominatedNumber) is provided by [`@reactive-dot/utils`](https://reactivedot.dev/api/utils).

```ts
import { DenominatedNumber } from "@reactive-dot/utils";

// Denominated numbers are created with a planck value and a decimal places number

const numberFromPlanck = new DenominatedNumber(10_000_000_000n, 10);

console.log(numberFromPlanck.valueOf()); // 10

// Denominated number can also be created from number instead of planck

const numberFromNumber = DenominatedNumber.fromNumber(10, 10);

console.log(numberFromNumber.planck); // 10000000000n

// A string denomination can optionally be added for locale string conversion capability

const numberWithDenomination = DenominatedNumber.fromNumber(10, 10, "DOT");

console.log(numberWithDenomination.toLocaleString("en-NZ")); // DOT 10.00

console.log(numberWithDenomination.toLocaleString("de-DE")); // 10,00 DOT

// Arithmetics

let dotAmount = DenominatedNumber.fromNumber(10, 10, "DOT");

// Arithmetic operations can be performed using the number's planck value

dotAmount = dotAmount.mapFromPlanck((planck) => planck + 5_000_000_000n);

console.log(dotAmount.toLocaleString()); // DOT 10.50

// Arithmetic operations can also be carried out with the number value
// instead of planck if possible lost of precision is acceptable

dotAmount = dotAmount.mapFromNumber((number) => (number * 2) / 4);

console.log(dotAmount.toLocaleString()); // DOT 5.25
```

0 comments on commit 9502eee

Please sign in to comment.