Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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