1

Floating point division is not supported in solidity as mentioned here: How can I perform float type division in solidity?

I want to divide two uint256 numbers and save them as a decimal, retaining 10 decimal places of accuracy. Would I need to multiply these numbers by 10000000000 first and then divide them by each other, then save the decimal and then divide the decimal by 10000000000?

0

If you have two uint a and b, and you wish, to divide a by b -> a/b with 10 decimals, then you can do the following

uint aScaled = a * 10**10;
uint divScaled = a / b;            // b is not scaled!

uint decN    = divScaled / 10**10;
uint decFrac = divScaled % 10**10

Example

a = 3; b = 2;
aScaled   = 3 * 10000000000;           // = 30000000000
divScaled = 30000000000 / 2;           // = 15000000000
decN      = 15000000000 / 10000000000; // = 1
decFrac   = 15000000000 mod 1000000000;// = 5000000000

I would keep the number scaled by 10**10 and present it only as a decimal in the UI.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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