Skip to content

Commit

Permalink
Merge pull request #14 from kduma-OSS/fix-rounding-error
Browse files Browse the repository at this point in the history
Fix rounding error
  • Loading branch information
kduma authored Apr 26, 2024
2 parents fd9c7e5 + 753efb5 commit 4db3926
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Values/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@ class Money
public function __construct(
public readonly int $amount,
public readonly int $decimals = 2,
) { }

) {
}

public static function fromFloat(float $amount, int $decimals = 2): static
{
return new static((int) ($amount * 10 ** $decimals), $decimals);
return new static(round($amount * 10 ** $decimals), $decimals);
}

public function __toString(): string
{
return number_format($this->toFloat(), $this->decimals, '.', '');
}

public function toFloat(): float
{
return $this->amount / 10 ** $this->decimals;
}
}
}

0 comments on commit 4db3926

Please sign in to comment.