From 6415d594f35ad4e003c5af52df19b7d05eda6555 Mon Sep 17 00:00:00 2001 From: Petr Heinz Date: Thu, 14 Feb 2019 14:57:16 +0100 Subject: [PATCH] fix Decimal::fromFloat() with specified lower scale - when created with a lower scale, innerRound is used (consistent with Decimal::fromString()) - covered by additional unit tests which fail without the code changes --- src/Decimal.php | 4 +++- tests/Decimal/DecimalFromFloatTest.php | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Decimal.php b/src/Decimal.php index 2a374ae..ede61b7 100644 --- a/src/Decimal.php +++ b/src/Decimal.php @@ -107,8 +107,10 @@ public static function fromFloat(float $fltValue, int $scale = null): Decimal if (null === $scale) { $scale = $naturalScale; - } else { + } elseif ($scale > $naturalScale) { $strValue .= ($hasPoint ? '' : '.') . \str_pad('', $scale - $naturalScale, '0'); + } else { + $strValue = self::innerRound($strValue, $scale); } } diff --git a/tests/Decimal/DecimalFromFloatTest.php b/tests/Decimal/DecimalFromFloatTest.php index 6ca042c..0500bb6 100644 --- a/tests/Decimal/DecimalFromFloatTest.php +++ b/tests/Decimal/DecimalFromFloatTest.php @@ -24,6 +24,17 @@ public function floatProvider() [-1.1234567890, "-1.123456789"], [0.000001, "0.0000010"], [0.000001, "0.00", 2], + [1.000001, "1.00", 2], + [-1.000001, "-1.00", 2], + [0, "0", 0], + [0, "0.0", 1], + [0, "0.00", 2], + [0.5, "1", 0], + [0.05, "0.1", 1], + [0.005, "0.01", 2], + [-0.5, "-1", 0], + [-0.05, "-0.1", 1], + [-0.005, "-0.01", 2], [90.05, "90.05"], ];