Skip to content

How to use Web3.Utils.formatToEthereumUnits() to parse a BigUint? #294

@AlleniCode

Description

@AlleniCode

If I get a token's decimal, and a BigUInt balance, how to format it to a string? THX!

Activity

dangell7

dangell7 commented on Dec 4, 2020

@dangell7
        var options = TransactionOptions.defaultOptions
        options.gasPrice = .automatic
        options.gasLimit = .automatic
        options.nonce = .latest
        options.from = signor
        let parameters: [EthereumAddress] = [signor]
        let tokenBalanceTx = contract.read(
            "balanceOf",
            parameters: parameters as [AnyObject],
            extraData: Data(),
            transactionOptions: options
        )
        let result = try? tokenBalanceTx?.call()
        guard let tokenWei = result?["0"] as? BigUInt else {
            print("FAILED ON PARSE RESULT")
            self.getBalanceDelegate?.getEthBalanceFailure(error: ErrorCodes().getError("CRYP1")) //BADC1
            return
        }
        guard let tokenBalance = Web3.Utils.formatToEthereumUnits(tokenWei) else {
            print("FAILED ON FORMAT TOKEN BALANCE")
            self.getBalanceDelegate?.getEthBalanceFailure(error: ErrorCodes().getError("CRYP1")) //BADC1
            return
        }
        guard let tokenIntBalance = Double(tokenBalance)?.rounded(toPlaces: 0) else {
            self.getBalanceDelegate?.getEthBalanceFailure(error: ErrorCodes().getError("CRYP1")) //BADC1
            return
        }
AlleniCode

AlleniCode commented on Dec 7, 2020

@AlleniCode
Author

My test code:

// USDT       0xdac17f958d2ee523a2206206994597c13d831ec7
// decimals   6
// 0.3 USDT

let decimals = 6
let balanceWithDecimals = "300000"
let balanceWithSymbol = "0.3"

let big = BigUInt.init(balanceWithDecimals, Web3.Utils.Units.wei)!
let result = Web3.Utils.formatToPrecision(big, numberDecimals: decimals, formattingDecimals: 8, decimalSeparator: ".", fallbackToScientific: false)
print(result)  // Optional("0.300000")
if Float(balanceWithSymbol) == Float(result as! String) {
     print("right")
} else {
     print("wrong")
}

@dangell7 Is this right?

dangell7

dangell7 commented on Dec 7, 2020

@dangell7

Is this after calling getBalance?

Or are you creating variables for interaction with a smart contract?

AlleniCode

AlleniCode commented on Dec 8, 2020

@AlleniCode
Author

@dangell7 Yes. The 'big' constant with type 'BigUInt' is the balance I got from a samrt contract.
Some code here:

...
let tx = contract.read()
let txResult = try? tx.call() as [String: Any]
let balance = txResult?["somekey"]
let balanceString = Web3.Utils.formatToPrecision(balance as! BigUInt, numberDecimals: tokenDecimals, formattingDecimals: 8, decimalSeparator: ".", fallbackToScientific: false)!
RaviRanjan-11

RaviRanjan-11 commented on Jan 1, 2021

@RaviRanjan-11
Contributor

You can use your own unit using web3Units

create Your Unit
let myUnit = Web3Units(rawValue: your deciamal Unit)

Fetch balance with web3 instance and your address
let balance = try? wInstance.eth.getBalance(address: yourEthAddress)

convert balance in to string
let balanceString = Web3.Utils.formatToEthereumUnits(balance ?? "0", toUnits: myUnit, decimals: 4)

Iysbaera

Iysbaera commented on Jun 29, 2021

@Iysbaera
Collaborator

@AlleniCode Hey, do you still have this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @skywinder@Iysbaera@AlleniCode@dangell7@RaviRanjan-11

        Issue actions

          How to use Web3.Utils.formatToEthereumUnits() to parse a BigUint? · Issue #294 · web3swift-team/web3swift