diff --git a/composer.json b/composer.json index d2fd22c..0cc2882 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ ], "require": { "php": "^7.4|^8.0", - "ext-bcmath": "*" + "ext-bcmath": "*", + "ext-json": "*" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.0", diff --git a/src/AbstractNumber.php b/src/AbstractNumber.php index c5373ed..fe53a76 100644 --- a/src/AbstractNumber.php +++ b/src/AbstractNumber.php @@ -9,7 +9,7 @@ use MadeByBob\Number\Exception\InvalidNumberInputTypeException; use MadeByBob\Number\Exception\InvalidRoundingModeException; -abstract class AbstractNumber +abstract class AbstractNumber implements \JsonSerializable { protected const INTERNAL_SCALE = 12; protected const DEFAULT_SCALE = 4; @@ -541,6 +541,14 @@ public function __toString(): string return $this->toString(); } + /** + * Converts the current MadeByBob\Number instance into a string. + */ + public function jsonSerialize() + { + return $this->toString(); + } + /** * @internal Provides value with internal scale. */ diff --git a/tests/NumberTest.php b/tests/NumberTest.php index 74720c0..b193419 100644 --- a/tests/NumberTest.php +++ b/tests/NumberTest.php @@ -699,4 +699,13 @@ public function testFormatNumber(): void $number = new Number('5943.000000'); $this->assertEquals('5.943', $number->format(0, 0)); } + + public function testCanJsonSerialize(): void + { + $number = new Number('9342.1557'); + $array = ['number' => $number]; + + $this->assertEquals('{"number":"9342.1557"}', json_encode($array)); + $this->assertEquals('"9342.1557"', json_encode($number)); + } }