Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: Farghaly on January 30, 2014, 11:38:54 AM



Title: Why add/subtract 0.5 while converting between JSON and amount
Post by: Farghaly on January 30, 2014, 11:38:54 AM
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   ???

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





Title: Re: Why add/subtract 0.5 while converting between JSON and amount
Post by: deepceleron on January 30, 2014, 02:43:01 PM
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   ???

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.