Icon HelpCircleForumIcon Link

⌘K

Icon HelpCircleForumIcon Link

Icon LinkNumbers

In Sway, there are multiple primitive number types:

  1. u8 (8-bit unsigned integer)
  2. u16 (16-bit unsigned integer)
  3. u32 (32-bit unsigned integer)
  4. u64 (64-bit unsigned integer)
  5. u256 (256-bit unsigned integer)

This guide explains how to create and interact with Sway numbers while using the SDK.

Icon LinkCreating Numbers

Icon LinkFor u64 and u256

When you pass in a u64 or a u256 to a Sway program from JavaScript, you must first convert it to a BigNum object. This is because these types can have extremely large maximum values (2^64 and 2^256 respectively), and JavaScript's Number type can only hold up to 53 bits of precision (2^53).

import { bn } from 'fuels';
 
const number: number | string = 20;
 
const bigNumber = bn(number);
 
console.log('equals', bigNumber.eqn(number));
// true

You can also create a BigNum from a string. This is useful when you want to pass in a number that is too large to be represented as a JavaScript number. Here's how you can do that:

import { bn } from 'fuels';
 
const strNumber = '9007199254740992';
 
const bigNumber = bn(strNumber);
 
console.log('equals', bigNumber.toString() === strNumber);
// true

Icon LinkFor u8, u16, and u32

You don't need to do anything special to create these numbers. You can pass in a JavaScript number directly. See the examples below for more details.

Icon LinkExamples: Interacting with Numbers in Contract Methods

Icon LinkFor u64 and u256

const bigNumber = bn('10000000000000000000');
 
const { value } = await contract.functions.echo_u64(bigNumber).get();
 
console.log('value', value.toString());
// '10000000000000000000'
Icon InfoCircle

Note: If a contract call returns a number that is too large to be represented as a JavaScript number, you can convert it to a string using the .toString() method instead of .toNumber().

Icon LinkFor u8, u16, and u32

const number = 200;
 
const { value } = await contract.functions.echo_u8(number).get();
 
console.log('value', Number(value));
// 200

Icon LinkUsing a BigNum from ethers with fuels

import { toBigInt } from 'ethers';
import { bn } from 'fuels';
 
const number = 20;
 
const ethersBigNum = toBigInt(number);
 
const fuelsBigNum = bn(ethersBigNum.toString());
 
console.log('value', fuelsBigNum.toNumber());
// 20