I just started writing some solidity and I noticed that there are no decimal values such as double or float.
What do you guys do when you need to return send to a wallet let's say 1.57 ether? Or when you need to calculate 1/2 = 0.5?
I'm very confused – I tried doing something like var a = 0.5;
but it gives me an error that says
Invalid literal value.
Best Answer
Math in Solidity is done entirely using fixed-point. For ether, there's no need to use fractional values - all values are represented in wei, which is the smallest unit of ether.
If you want to send 0.5 ether, you can instead specify your literal as "500 finney", which will be converted into wei:
or:
which are both exactly equivalent to:
If you want to multiply a value by a fraction (eg, 2/3), first multiply by the numerator, then divide by the denominator:
It's worth noting, too, that floating point for financial math is a terrible idea - it introduces rounding errors that easily lead to lost money.