self::MAX_QUARTERS) { throw new InvalidWorkedHours; } $this->quarters = $quarters; } /** * Parses "2,5", "2.5" or "2"; null for an empty value. * * @throws InvalidWorkedHours */ public static function parse(string $value): ?self { $value = str_replace(',', '.', trim($value)); if ($value === '') { return null; } if (! is_numeric($value)) { throw new InvalidWorkedHours; } $quarters = (float) $value * 4; if (abs($quarters - round($quarters)) > 1e-9) { throw new InvalidWorkedHours; } return new self((int) round($quarters)); } public static function fromDecimal(float $hours): self { return new self((int) round($hours * 4)); } public function decimal(): float { return $this->quarters / 4; } public function plus(self $other): self { return new self($this->quarters + $other->quarters); } /** * Finnish notation without trailing zeros, e.g. "7,5" or "8". */ public function format(): string { return self::formatQuarters($this->quarters); } public static function formatQuarters(int $quarters): string { return str_replace('.', ',', rtrim(rtrim(number_format($quarters / 4, 2, '.', ''), '0'), '.')); } }