简体   繁体   中英

How to get the final value from Chainlink Data feeds in decimals?

Was writing a NFT contract where to mint a single token requires ETH equivalent to 40000 USD. So figured out to use ChainLink data feeds for conversion. Apparently they return the value in whole numbers which is not required.

Here's the code

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Rinkeby
     * Aggregator: ETH/USD
     * Address: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e
     */
    constructor() {
        priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
    }

    /**
     * Returns the latest price
     */
    function getLatestPrice() public view returns (uint) {
        (
            uint80 roundID,
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        uint8 Decimals = priceFeed.decimals();
        uint Price = uint(price);
        return Price/10**Decimals;
    }

}

Here is the value that I received when tested on Remix when I did not divide it by the decimals. Result1

Here is the value that I received when tested on Remix when I divide it by the decimals. Result2

How do I get 3165.27730535 here.

From latest updated documentation:

Fixed point numbers are not fully supported by Solidity yet. They can be declared, but cannot be assigned to or from.

Said this, you can convert the uint to string and try to handle this types like floating point variables. You can see more abou this operation here .

I don't see any advantage in converting it to decimal. If you need to display it in decimal on the front-end just convert it there.

Otherwise you can search some library on google (like this one )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM