Skip to content

Commit

Permalink
fix: number_format 精度问题 (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
krissss authored Jul 19, 2024
1 parent 150c652 commit d030fda
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/BCS.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,20 @@ public function isLargerThan($number)
/**
* 格式化数字
* @param $number
* @return string
* @return string|float|int
*/
private function numberFormat($number): string
private function numberFormat($number)
{
if (is_string($number) && strpos($number, 'E') === false && strpos($number, 'e') === false) {
return $number;
if (is_float($number)) {
// 将 float 转为 string,科学计数法可以正常变成 8.0E-6
$number = (string)$number;
}
if (
is_string($number)
&& (strpos($number, 'E') !== false || strpos($number, 'e') !== false) // 科学计数法
) {
return number_format($number, $this->config['operateScaleNumberFormat'], '.', '');
}
return number_format($number, $this->config['operateScale']+1, '.', '');
return $number;
}
}
1 change: 1 addition & 0 deletions src/BaseBC.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ abstract class BaseBC
public $config = [
'scale' => null, // 精度,为 null 会取 ini 中的配置,否则为 0
'operateScale' => 18, // 操作过程中的计算精度
'operateScaleNumberFormat' => 15, // 操作过程中的 number_format 的精度,超过15位会存在精度丢失
'round' => false, // 是否四舍五入,当向上和舍位都为 false 时,默认为四舍五入
'ceil' => false, // 是否向上取数,当有小数位时精度末位向上取
'floor' => false, // 是否舍位,当有小数位时舍去精度之后的
Expand Down
11 changes: 11 additions & 0 deletions tests/IssueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,14 @@
$result = BCS::create('1233123131432143214321412.123')->compare('1233123131432143214321411.123');
expect($result)->toEqual(1);
});

test('issue-11', function () {
$a = BCS::create(1.66, ['scale' => 2]);
$l = [
0.110000,0.110000, 0.110000, 0.090000, 0.080000, 0.080000, 0.050000, 0.050000, 0.050000, 0.050000, 0.050000, 0.110000, 0.110000, 0.110000, 0.090000, 0.080000, 0.080000, 0.050000, 0.050000, 0.050000, 0.050000,0.050000];
foreach ($l as $_l) {
expect($a->isLessThan($_l))->toBeFalse();
$a->sub($_l);
}
expect($a->getResult())->toBe(0.0);
});

0 comments on commit d030fda

Please sign in to comment.