Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: Remember remember the 5th of November on April 26, 2013, 05:38:01 AM



Title: Storing Bitcoin precision numbers with PHP.
Post by: Remember remember the 5th of November on April 26, 2013, 05:38:01 AM
I am writing an exchange in PHP as an exercise to see how they work, just an exercise nothing for real-world application. I haven't done PHP in a very long time I have become so rusty many basics are still hard to remember.

I want to store a number of say 87.12471115 bitcoins as a 64bit integer in MySQL(i), where my field is of type BIGINT. I want to store it without any precision loss, or need for rounding so that no matter what number is entered it's ALWAYS printed exactly the same way it was entered, not even a single digit being higher or lower.

Like entering 87.12471115 and then fetching the value as 87.12471116 or 87.12471114 or even worse 87.13 <-- BAD.

So how do I process the number? In Bitcoin it's multiplied by 100,000,000(64bit integer) which a hundred million.

Code:
<?php

$amount 
$_POST['amount']; // the user has entered 87.12471115 which gets interpreted either as a string OR a double.

// what should be done here?

mysqli_query(....); // insert the amount here

As you can see it either gets treated as a double or a string. How would the process of double to integer happen?


Title: Re: Storing Bitcoin precision numbers with PHP.
Post by: lucif on April 26, 2013, 05:46:50 AM
I think the following

Code:
$amount_int64=bcmul($amount,'100000000',0);

EDIT: keep in mind, BCmath keeps large numbers as string variables. So your $amount_int64 will be a string for php.


Title: Re: Storing Bitcoin precision numbers with PHP.
Post by: Bitsky on April 26, 2013, 03:26:02 PM
Or store them as Satoshi. Int on 64bit system should be large enough to handle them.