You really should not use floating point math for precision decimal values. It is a little-regarded truth of computer programming that when you're dealing with money you should avoid the usual IEEE floating-point math like the plague.
This is the reason why Bitcoin transactions store values as 64-bit integers. Because storing them as floating point numbers is error-prone.
For example, in your interactive PHP shell you can do something like this to find out where your math begins to break:
php > echo 10000.00000001 * 2;
20000.00000002
php > echo 100000.00000001 * 2;
200000.00000002
php > echo 1000000.00000001 * 2;
2000000
I'm running 64-bit PHP, too. If you are running 32-bit PHP the situation becomes pretty dire.
The take-away here is that overall precision of floating point numbers is limited. The bigger your number, the fewer meaningful decimal places it can have.
The correct way to address this problem is to use PHP's BC Math functions. You keep your data as strings, and BCMath will let you perform arbitrary-precision computations. It isn't as fast as floating point math, but it isn't exactly slow either.
/** Convert Satoshis to a string that can be displayed to users.
* input: $value Integer or string that can be parsed as an int.
* output: string (eg: "1.00400000")
*/
function convertToBTCFromSatoshi($value){
return bcdiv( intval($value), 100000000, 8 );
}
If you want to trim the zeros from the end of the output, you can use the trim()
function:
rtrim($value, "0"); // trim zeros from the right-hand side