Skip to content

Commit

Permalink
add json serialize (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
Melvin Drost authored Oct 24, 2022
1 parent e288f8e commit cf31a7e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
],
"require": {
"php": "^7.4|^8.0",
"ext-bcmath": "*"
"ext-bcmath": "*",
"ext-json": "*"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
Expand Down
10 changes: 9 additions & 1 deletion src/AbstractNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*/
Expand Down
9 changes: 9 additions & 0 deletions tests/NumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit cf31a7e

Please sign in to comment.