> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Convert decimals to hex with web3.js and ethers.js

> Hexadecimal strings are used to represent addresses and encode gas data and values. These scripts show you how to do it programmatically within your DApps.

<AccordionGroup>
  <Accordion title="Overview">
    Converting decimal to hexadecimal is a standard operation in Web3; let's see how to do it using two of the popular JavaScript libraries:

    * web3.js
    * ethers.js (V6)
  </Accordion>

  <Accordion title="Environment setup">
    Install [node.js](https://nodejs.org/) in case it is not installed yet.

    Create a new directory for your project, then install the web3.js and ethers.js libraries:

    `npm install web3 ethers`
  </Accordion>

  <Accordion title="Function to convert decimal to hex">
    The web3.js library uses the `utils.toHex()` function to take care of this operation, while ethers V6 uses the `toBeHex()` function.

    The scripts show how to use those functions and log the result.

    <CodeGroup>
      ```js web3 theme={"system"}
      return Web3.utils.toHex(decimalNumber);
      ```

      ```js ethers theme={"system"}
      return ethers.toBeHex(decimalNumber);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Run the script">
    Now you can run the scripts from the terminal and see the results displayed.

    `node YOUR_SCRIPTS_NAME`
  </Accordion>
</AccordionGroup>

<RequestExample>
  ```js web3 theme={"system"}
  const Web3 = require("web3");

  function decimalToHexadecimal(decimalNumber) {
    return Web3.utils.toHex(decimalNumber);
  }

  // Run the function and log the result
  const decimalNumber = 255;
  const hexadecimalNumber = decimalToHexadecimal(decimalNumber);
  console.log(
    `The hexadecimal representation of ${decimalNumber} is ${hexadecimalNumber}`
  );

  ```

  ```js ethers theme={"system"}
  const ethers = require("ethers");

  function decimalToHexadecimal(decimalNumber) {
    return ethers.toBeHex(decimalNumber);
  }

  // Run the function and log the result
  const decimalNumber = 255;
  const hexadecimalNumber = decimalToHexadecimal(decimalNumber);
  console.log(
    `The hexadecimal representation of ${decimalNumber} is ${hexadecimalNumber}`
  );
  ```
</RequestExample>

<ResponseExample>
  ```bash theme={"system"}
  The hexadecimal representation of 255 is 0xff
  ```
</ResponseExample>
