Skip to content
This repository was archived by the owner on Dec 27, 2023. It is now read-only.

Commit 9b90b32

Browse files
author
Andrés Correa Casablanca
authored
Merge pull request #61 from precariouspanther/ISSUE-60-float-innerlog10-div-zero
ISSUE-60: Fix for division by zero caused by float precision
2 parents edea342 + 86cc13c commit 9b90b32

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/Decimal.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1203,6 +1203,7 @@ private static function innerLog10(string $value, int $in_scale, int $out_scale)
12031203
switch ($cmp) {
12041204
case 1:
12051205
$value_log10_approx = $value_len - ($in_scale > 0 ? ($in_scale+2) : 1);
1206+
$value_log10_approx = max(0, $value_log10_approx);
12061207

12071208
return \bcadd(
12081209
(string)$value_log10_approx,

tests/regression/issue60Test.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Litipk\BigNumbers\Decimal;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class issue60Test extends TestCase
9+
{
10+
public function test_that_fromFloat_division_does_not_calculate_invalid_log10_avoiding_div_zero()
11+
{
12+
$value = Decimal::fromFloat(1.001);
13+
$divisor = Decimal::fromFloat(20);
14+
15+
$this->assertEquals(0.05005, $value->div($divisor)->asFloat());
16+
$this->assertEquals(0.000434077479319, $value->log10()->asFloat());
17+
}
18+
19+
public function test_that_fromFloat_less_than_1_still_correct()
20+
{
21+
$value = Decimal::fromFloat(0.175);
22+
$divisor = Decimal::fromFloat(20);
23+
24+
$this->assertEquals(0.009, $value->div($divisor)->asFloat());
25+
$this->assertEquals(-0.7569, $value->log10()->asFloat());
26+
}
27+
}

0 commit comments

Comments
 (0)