Last active
December 17, 2015 01:39
-
-
Save picasso250/5530014 to your computer and use it in GitHub Desktop.
计算时指定精度,适用于计算财务
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function dec_calc($a, $b, $p, $func, $fp) | |
{ | |
for ($m=1,$i=0; $i < $p; $i++) { | |
$m *= 10; | |
} | |
$aa = $a*$m; | |
$bb = $b*$m; | |
$r = $func($aa, $bb); | |
for ($d=1,$i=0; $i < $fp; $i++) { | |
$d *= $m; | |
} | |
return round($r / $d, $p); | |
} | |
function logs($str, $level) | |
{ | |
echo "<p>$str</p>\n"; | |
} | |
function dec_add($a, $b, $p) | |
{ | |
return dec_calc($a, $b, $p, function($a,$b){return $a+$b}, 1); | |
} | |
function dec_sub($a, $b, $p) | |
{ | |
return dec_calc($a, $b, $p, function($a,$b){return $a-$b}, 1); | |
} | |
function dec_multi($a, $b, $p) | |
{ | |
return dec_calc($a, $b, $p, function($a,$b){return $a*$b}, 2); | |
} | |
function dec_div($a, $b, $p) | |
{ | |
return dec_calc($a, $b, $p, function($a,$b){return $a/$b}, 0); | |
} | |
var_dump( | |
dec_calc( | |
dec_calc( | |
0.1, | |
0.72, | |
2, | |
function ($a, $b) {return $a+$b;}, | |
1 | |
), | |
10, | |
2, | |
function ($a, $b) {return $a*$b;}, | |
2 | |
) | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* | |
*/ | |
class MoneyDec | |
{ | |
public $val; | |
public $pr; | |
public $int; | |
public function __construct($val, $pr) | |
{ | |
$this->int = $this->val = $val; | |
$this->pr = $pr; | |
for ($this->m=1, $i=0; $i < $pr; $i++) { | |
$this->int *= 10; | |
$this->m *= 10; | |
} | |
$this->int = (int) round($this->int); | |
} | |
public function __s | |
} | |
function dec_add(MoneyDec $a, MoneyDec $b) | |
{ | |
$aint = $a->int; | |
$bint = $b->int; | |
// 对齐 | |
// 寻找小的,乘以商 | |
if ($a->pr == $b->pr) { | |
} elseif ($a->pr < $b->pr) { | |
$aint *= $b->m / $a->m; | |
} else { | |
$bint *= $a->m / $b->m; | |
} | |
$rint = $aint + $bint; | |
return new MoneyDec($rint / max($a->m, $b->m), max($a->pr, $b->pr)); | |
} | |
function logs($str, $level) | |
{ | |
echo "<p>$str</p>\n"; | |
} | |
$a = new MoneyDec(0.1, 8); | |
$b = new MoneyDec(0.7, 2); | |
$c = dec_add($a, $b, function($a,$b){return $a+$b;}); | |
var_dump($c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment