Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/Services/FormatterService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Services;

use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;

final readonly class FormatterService implements FormatterServiceInterface
{
public function intValue(string|int|float $amount, int $decimalPlaces): string
{
return (string) BigDecimal::ten()
->power($decimalPlaces)
->multipliedBy(BigDecimal::of($amount))
->toScale(0, RoundingMode::DOWN);
}

public function floatValue(string|int|float $amount, int $decimalPlaces): string
{
return (string) BigDecimal::ofUnscaledValue($amount, $decimalPlaces);
}
}
15 changes: 15 additions & 0 deletions src/Services/FormatterServiceInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Services;

/**
* @internal
*/
interface FormatterServiceInterface
{
public function intValue(string|int|float $amount, int $decimalPlaces): string;

public function floatValue(string|int|float $amount, int $decimalPlaces): string;
}
55 changes: 55 additions & 0 deletions tests/Units/Service/FormatterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace Bavix\Wallet\Test\Units\Service;

use Bavix\Wallet\Internal\Exceptions\ExceptionInterface;
use Bavix\Wallet\Services\FormatterServiceInterface;
use Bavix\Wallet\Test\Infra\TestCase;

/**
* @internal
*/
final class FormatterTest extends TestCase
{
/**
* @throws ExceptionInterface
*/
public function testFloatValueDP3(): void
{
$result = app(FormatterServiceInterface::class)->floatValue('12345', 3);

self::assertSame('12.345', $result);
}

/**
* @throws ExceptionInterface
*/
public function testFloatValueDP2(): void
{
$result = app(FormatterServiceInterface::class)->floatValue('12345', 2);

self::assertSame('123.45', $result);
}

/**
* @throws ExceptionInterface
*/
public function testIntValueDP3(): void
{
$result = app(FormatterServiceInterface::class)->intValue('12.345', 3);

self::assertSame('12345', $result);
}

/**
* @throws ExceptionInterface
*/
public function testIntValueDP2(): void
{
$result = app(FormatterServiceInterface::class)->intValue('123.45', 2);

self::assertSame('12345', $result);
}
}