Author

Topic: Why add/subtract 0.5 while converting between JSON and amount (Read 677 times)

legendary
Activity: 1512
Merit: 1036
In this wiki article "Proper Money Handling"
https://en.bitcoin.it/wiki/Proper_Money_Handling_(JSON-RPC)

Why add 0.5 if value is more than 0.0, and subtract 0.5 if value less than 0.0   Huh

Code:
int64_t JSONtoAmount(double value) {
    return (int64_t)(value * 1e8 + (value < 0.0 ? -.5 : .5));
}

This is a way to achieve deterministic rounding when storing as an integer

3.425 rounds to 3; 3.531 rounds to 4
the int of 3.425 + 0.5 is 3; the int() of 3.531 + 0.5 = 4.031 is 4.

Since bitcoin amounts on the network can only have accuracy down to satoshis, you may have to do rounding on maths which would have a sub-satoshi remainder. An imaginary example would be an exchange that pays you the average price of three other exchanges. (a+b+c)/3 * (1/dollars) may be an irrational result like 166.66666666666666; what the exchange pays in BTC should round up to 166.66666667 if they are fair.
newbie
Activity: 38
Merit: 0
In this wiki article "Proper Money Handling"
https://en.bitcoin.it/wiki/Proper_Money_Handling_(JSON-RPC)

Why add 0.5 if value is more than 0.0, and subtract 0.5 if value less than 0.0   Huh

Code:
int64_t JSONtoAmount(double value) {
    return (int64_t)(value * 1e8 + (value < 0.0 ? -.5 : .5));
}



Jump to: