self::MAX_TENTHS) { throw new InvalidKilometers; } $this->tenths = $tenths; } /** * Parses "12", "12,5" or "12.5"; null for an empty value. * * @throws InvalidKilometers */ public static function parse(string $value): ?self { $value = str_replace(',', '.', preg_replace('/[\s\x{00A0}]+|km/u', '', $value) ?? ''); if ($value === '') { return null; } if (preg_match('/^(\d{1,6})(?:\.(\d))?$/', $value, $matches) !== 1) { throw new InvalidKilometers; } return new self((int) $matches[1] * 10 + (int) ($matches[2] ?? 0)); } /** * The price of these kilometres at a rate per kilometre, rounded half up to the cent. */ public function priceAt(Money $ratePerKilometer): Money { return Money::fromCents(intdiv($this->tenths * $ratePerKilometer->cents * 2 + 10, 20)); } /** * Finnish notation, e.g. "12,5" or "40". */ public function format(): string { return $this->tenths % 10 === 0 ? (string) intdiv($this->tenths, 10) : intdiv($this->tenths, 10).','.($this->tenths % 10); } }