Updated answer, for newer Solidity version, also making use of the Exchange Rate system contract from HIP-475,
which is available at 0x168
, with the following interface:
interface IExchangeRate {
function tinycentsToTinybars(uint256 tinycents) external returns (uint256);
function tinybarsToTinycents(uint256 tinybars) external returns (uint256);
}
As long as your use case does require a high degree of accuracy or "liveness",
this does an OK job of the conversion.
The following example demonstrates how to use the exchange rate system contract
to convert from USD cents to HBAR cents.
Try it out in Remix
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.18;
interface IExchangeRate {
// Given a value in tinycents (1e-8 US cents or 1e-10 USD), returns the
// equivalent value in tinybars (1e-8 HBAR) at the current exchange rate
// stored in system file 0.0.112.
//
// This rate is a weighted median of the the recent" HBAR-USD exchange
// rate on major exchanges, but should _not_ be treated as a live price
// oracle! It is important primarily because the network will use it to
// compute the tinybar fees for the active transaction.
//
// So a "self-funding" contract can use this rate to compute how much
// tinybar its users must send to cover the Hedera fees for the transaction.
function tinycentsToTinybars(uint256 tinycents) external returns (uint256);
// Given a value in tinybars (1e-8 HBAR), returns the equivalent value in
// tinycents (1e-8 US cents or 1e-10 USD) at the current exchange rate
// stored in system file 0.0.112.
//
// This rate tracks the the HBAR-USD rate on public exchanges, but
// should _not_ be treated as a live price oracle! This conversion is
// less likely to be needed than the above conversion from tinycent to
// tinybars, but we include it for completeness.
function tinybarsToTinycents(uint256 tinybars) external returns (uint256);
}
contract Exchange {
IExchangeRate constant ExchangeRate =
IExchangeRate(address(0x168));
event ConversionResult(uint256 inAmount, uint256 outAmount);
function convert(uint256 usdCents) external returns (uint256 hbarCents) {
hbarCents = ExchangeRate.tinycentsToTinybars(usdCents * 100_000_000) / 1_000_000;
emit ConversionResult(usdCents, hbarCents);
}
}
Note that as of time of writing, 1,000.00 USD is 19,584.80 HBAR.

However an input of 100,000 (usdCents
) returns an output of 1,969,667 (hbarCents
),
which is approximately 0.6% off of the live value.
So don't use this in a DEX or anything like that.