Skip to content

Commit cf31a7e

Browse files
author
Melvin Drost
authored
add json serialize (#16)
1 parent e288f8e commit cf31a7e

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

composer.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
],
1818
"require": {
1919
"php": "^7.4|^8.0",
20-
"ext-bcmath": "*"
20+
"ext-bcmath": "*",
21+
"ext-json": "*"
2122
},
2223
"require-dev": {
2324
"friendsofphp/php-cs-fixer": "^3.0",

src/AbstractNumber.php

+9-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use MadeByBob\Number\Exception\InvalidNumberInputTypeException;
1010
use MadeByBob\Number\Exception\InvalidRoundingModeException;
1111

12-
abstract class AbstractNumber
12+
abstract class AbstractNumber implements \JsonSerializable
1313
{
1414
protected const INTERNAL_SCALE = 12;
1515
protected const DEFAULT_SCALE = 4;
@@ -541,6 +541,14 @@ public function __toString(): string
541541
return $this->toString();
542542
}
543543

544+
/**
545+
* Converts the current MadeByBob\Number instance into a string.
546+
*/
547+
public function jsonSerialize()
548+
{
549+
return $this->toString();
550+
}
551+
544552
/**
545553
* @internal Provides value with internal scale.
546554
*/

tests/NumberTest.php

+9
Original file line numberDiff line numberDiff line change
@@ -699,4 +699,13 @@ public function testFormatNumber(): void
699699
$number = new Number('5943.000000');
700700
$this->assertEquals('5.943', $number->format(0, 0));
701701
}
702+
703+
public function testCanJsonSerialize(): void
704+
{
705+
$number = new Number('9342.1557');
706+
$array = ['number' => $number];
707+
708+
$this->assertEquals('{"number":"9342.1557"}', json_encode($array));
709+
$this->assertEquals('"9342.1557"', json_encode($number));
710+
}
702711
}

0 commit comments

Comments
 (0)