moontoast / math

A PHP 5.3+ mathematics library, providing functionality for large numbers
Apache License 2.0
247 stars 31 forks source link

Does it work well with floating point numbers too #3

Open CMCDragonkai opened 10 years ago

CMCDragonkai commented 10 years ago

I'm new the math calculations in PHP. But I noticed your library focused on BIG integers. What about deep floating point numbers? Can I use it to accurately calculate that? Or would I need to convert decimals to integers before using your library.

ramsey commented 10 years ago

Operations on large floating point numbers are possible, but you'll need to specify the scale to use (second argument on the constructor), otherwise the BCMath functions will truncate the number.

For example:

$bn = new \Moontoast\Math\BigNumber('9,223,372,036,854,775,808.12345678901234567890', 20);
$bn->multiply(100);

var_dump($bn->getValue());

This results in:

string(42) "922337203685477580812.34567890123456789000"

You can then change the scale, like this:

$bn->setScale(4);
$bn->add(1);
var_dump($bn->getValue());

Which results in:

string(26) "922337203685477580813.3456"

Note that changing the scale does not round up/down the floating point number. It simply truncates it.

Does this help?

CMCDragonkai commented 10 years ago

What's the max scale? And would it be possible to autodetect the necessary scale? Especially when you don't know the max scale required before you multiply two numbers.