Bitcoin Forum
June 14, 2024, 07:13:20 AM *
News: Voting for pizza day contest
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: Why add/subtract 0.5 while converting between JSON and amount  (Read 649 times)
Farghaly (OP)
Newbie
*
Offline Offline

Activity: 38
Merit: 0


View Profile
January 30, 2014, 11:38:54 AM
 #1

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));
}



deepceleron
Legendary
*
Offline Offline

Activity: 1512
Merit: 1032



View Profile WWW
January 30, 2014, 02:43:01 PM
 #2

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.
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!