From fe2c5676e1532ecefd2c7088e1d84c86b12a253b Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Fri, 5 Mar 2021 20:58:08 +0100 Subject: [PATCH] auto format decimals --- Localization/Money.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Localization/Money.php b/Localization/Money.php index 021c47980..20962f249 100644 --- a/Localization/Money.php +++ b/Localization/Money.php @@ -170,13 +170,13 @@ final class Money implements \Serializable /** * Get money. * - * @param int $decimals Precision + * @param int $decimals Precision (null = auto decimals) * * @return string * * @since 1.0.0 */ - public function getCurrency(int $decimals = 2) : string + public function getCurrency(?int $decimals = 2) : string { return ($this->position === 0 && !empty($this->symbol) ? $this->symbol . ' ' : '') . $this->getAmount($decimals) . ($this->position === 1 ? ' ' . $this->symbol : ''); } @@ -184,7 +184,7 @@ final class Money implements \Serializable /** * Get money. * - * @param int $decimals Precision + * @param null|int $decimals Precision (null = auto decimals) * * @return string * @@ -192,7 +192,7 @@ final class Money implements \Serializable * * @since 1.0.0 */ - public function getAmount(int $decimals = 2) : string + public function getAmount(?int $decimals = 2) : string { $value = $this->value === 0 ? \str_repeat('0', self::MAX_DECIMALS) @@ -208,6 +208,10 @@ final class Money implements \Serializable throw new \Exception(); // @codeCoverageIgnore } + if ($decimals === null) { + $decimals = \strlen(\rtrim($right, '0')); + } + return $decimals > 0 ? \number_format((float) $left, 0, $this->decimal, $this->thousands) . $this->decimal . \substr($right, 0, $decimals) : \str_pad($left, 1, '0');