2

What is your strategy for storing and displaying decimal places for ETH?

I noticed most exchanges use only 4 (Binance) to 8 (CEX) decimal places when displaying ETH amount. What is your take?

And do you actually store the entire 18-digit fraction in your dapp backend or smart contract?

2 Answers 2

3

If the amount is in Wei or another unit, you'll need to convert it to Ether before displaying it in ETH format. The conversion depends on the unit in which the amount is provided. For example:

to convert from Wei to Ether you need to divide the amount by 10^18.

To convert from Gwei to Ether you need to divide the amount by 10^9.

Here are some examples in js:

const amountWei = 5000000000000000000; // Amount in Wei
const amountEth = amountWei / 1e18; // Convert from Wei to ETH
const formattedAmount = amountEth.toFixed(4); // Limit to 4 decimal places
console.log(`${formattedAmount} ETH`); // Displays "5.0000 ETH"

const amountGwei = 2500000000; // Amount in Gwei
const amountEth = amountGwei / 1e9; // Convert from Gwei to ETH
const formattedAmount = amountEth.toFixed(4); // Limit to 4 decimal places
console.log(`${formattedAmount} ETH`); // Displays "0.0025 ETH"

here are some examples to store eth in solidity:

uint constant public ONE_ETH = 1000000000000000000; // 1 Ether en Wei
uint constant public HALF_ETH = 500000000000000000; // 0.5 Ether en Wei

In Solidity, you can represent an amount of Ether using the uint data type, which is an unsigned integer of 256 bits. The amount must be specified in units of Wei, which is the smallest unit of Ether. Therefore, to represent an amount of Ether in Solidity, you need to specify it in terms of its equivalent in Wei.

To store data, you must always save it in Wei and make the corresponding conversions to display it in the UI/UX. the Ethereum network always works with Wei for its transactions, it is preferable to keep the network format and only make the necessary conversions for UI purposes.

1

The way it is displayed in different exchanges is just a mere choice of visual representation for front ends. Ether has 18 zeros after decimal points. The smallest unit of Ether is Wei:

1 Wei = 0.000000000000000001 Ether

1 Ether = 1000000000000000000 (10^18) Wei

Dapps and contracts natively store and transact in Wei, so there is really no need to store decimal places. It is your personal choice and preference how you decide to display it in your front end.

This article explains it really well and has some examples: What are the Different Units Used in Ethereum?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.