Skip to content

Instantly share code, notes, and snippets.

@dereckson
Created March 19, 2018 11:51
Show Gist options
  • Save dereckson/235e573ecb0af00b1b99ac258fab1adf to your computer and use it in GitHub Desktop.
Save dereckson/235e573ecb0af00b1b99ac258fab1adf to your computer and use it in GitHub Desktop.
How to perform 14 * 10^-15?
<?php
use Brick\Math\BigDecimal;
require 'vendor/autoload.php';
$left = BigDecimal::of(14);
$right = BigDecimal::one()->toScale(15)->dividedBy(BigDecimal::ten()->power(15));
$product = $left->multipliedBy($right);
echo $product, "\n";
/**
* Two things important to note:
*
* - By default, bc and gmp will work with integer, we need explicitly to tell them they need to work with decimal
* - By default, bc has an absurdly low scale for decimal (4), we need explicitly to choose the scale of precision
* That's the job of ->toScale(15), it means store 15 digits for the decimal part.
*
* There is perhaps a wrapper for scientific notation (I hope so), as it can be cumbersome to write long expressions.
* If not, commit that to the lib would be a good move.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment