Ethers BigNumber to USD conversion

608 views Asked by At

I'm trying to convert an Ethereum value to its retrospective fiat value. The final value of USD seems wrong, and I wonder if it's how it's calculated with big numbers.

I've attached a sandbox for convenience. https://codesandbox.io/s/autumn-sun-0k02d5?file=/src/index.js

Attempt

const one = parseUnits("1");
const price = parseUnits("0.1");
const _rate = "1563.48";
const rate = parseUnits(_rate, 2);
const usdPrice = price.lt(one) ? rate.mul(price) : rate.div(price);

Expectation: usdPrice = 156.348

Actual: usdPrice = 15634.8

1

There are 1 answers

0
Nico Halpe On

Try this code:

import { formatEther, parseEther } from "@ethersproject/units";

// const price = parseUnits("0.00000000000000001");
// const price = parseUnits("0.00000001000000000");
const price = parseEther("0.1");
const _rate = "1563.48";
const rate = parseFloat(_rate);
const usdPrice = rate * price;

document.getElementById("app").innerHTML = `
<p>Price in Eth ${formatEther(price)}</p>
<p>Price in USD ${formatEther(usdPrice.toString())}</p>
<p>1 ETH = ${rate}</p>
<p>Balance: ${formatEther(price)} Rate: ${rate}</p>
`;

Since the rate is in dollars, you should parse it to a float, not to gwai.