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

Commit 00386d6

Browse files
author
Andrés Correa Casablanca
committed
Fix issue 55
1 parent bb64b59 commit 00386d6

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/Decimal.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ public static function fromFloat(float $fltValue, int $scale = null): Decimal
9191
}
9292

9393
$strValue = (string) $fltValue;
94+
$hasPoint = (false !== \strpos($strValue, '.'));
95+
9496
if (\preg_match(self::EXP_NUM_GROUPS_NUMBER_REGEXP, $strValue, $capture)) {
9597
if (null === $scale) {
9698
$scale = ('-' === $capture['sign'])
@@ -99,12 +101,14 @@ public static function fromFloat(float $fltValue, int $scale = null): Decimal
99101
}
100102
$strValue = \number_format($fltValue, $scale, '.', '');
101103
} else {
102-
$naturalScale = \strlen((string)fmod($fltValue, 1.0)) - 2 - (($fltValue < 0) ? 1 : 0);
104+
$naturalScale = (
105+
\strlen((string)\fmod($fltValue, 1.0)) - 2 - (($fltValue < 0) ? 1 : 0) + (!$hasPoint ? 1 : 0)
106+
);
103107

104108
if (null === $scale) {
105109
$scale = $naturalScale;
106110
} else {
107-
$strValue .= str_pad('', $scale - $naturalScale, '0');
111+
$strValue .= ($hasPoint ? '' : '.') . \str_pad('', $scale - $naturalScale, '0');
108112
}
109113
}
110114

tests/regression/issue55Test.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Litipk\BigNumbers\Decimal;
6+
use PHPUnit\Framework\TestCase;
7+
8+
class issue55Test extends TestCase
9+
{
10+
public function test_that_forcing_concrete_precision_on_creation_does_not_corrupt_the_passed_value()
11+
{
12+
$this->assertEquals(4.0, Decimal::create(4.0, 8)->asFloat());
13+
}
14+
}

0 commit comments

Comments
 (0)