self::MAX_CENTS) { throw new InvalidMoneyAmount; } $this->cents = $cents; } public static function fromCents(int $cents): self { return new self($cents); } /** * Parses "85", "85,50", "85.5", "1 200,00" or "85 €"; null for an empty value. * * @throws InvalidMoneyAmount */ public static function parse(string $value): ?self { $value = preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? ''; $value = str_replace(',', '.', $value); if ($value === '') { return null; } if (preg_match('/^(\d{1,9})(?:\.(\d{1,2}))?$/', $value, $matches) !== 1) { throw new InvalidMoneyAmount; } $fraction = str_pad($matches[2] ?? '', 2, '0'); return new self((int) $matches[1] * 100 + (int) $fraction); } /** * This amount without VAT plus the VAT, rounded half up to the cent. */ public function addVat(VatPercentage $vat): self { return new self(intdiv($this->cents * (10_000 + $vat->basisPoints) * 2 + 10_000, 20_000)); } /** * The amount without VAT when this amount includes it, rounded half up to the cent. */ public function removeVat(VatPercentage $vat): self { $divisor = 10_000 + $vat->basisPoints; return new self(intdiv($this->cents * 10_000 * 2 + $divisor, $divisor * 2)); } /** * Finnish notation with the currency, e.g. "1 200,50 €". */ public function format(): string { return $this->amount(self::NO_BREAK_SPACE).self::NO_BREAK_SPACE.'€'; } /** * The amount for an input field, e.g. "1200,50". */ public function inputValue(): string { return $this->amount(''); } private function amount(string $thousandsSeparator): string { return number_format($this->cents / 100, 2, ',', $thousandsSeparator); } }