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
40 changes: 37 additions & 3 deletions src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,45 @@ public function extractValue(): string

[$digits, $decimals] = array_pad(explode('.', $matches[1]), 2, '0');

$decimals = substr(strval(round(floatval('0.' . $decimals), 2)), 2);
$negative = str_starts_with($digits, '-');
$whole = ltrim($digits, '-');
if($whole === '') {
$whole = '0';
}

$rounded = number_format(round(floatval('0.' . $decimals), 2), 2, '.', '');
[$carry, $cents] = explode('.', $rounded);
if($carry === '1') {
$whole = $this->increment($whole);
}

$value = ltrim($whole . $cents, '0');
if($value === '') {
$value = '0';
}
if($negative && $value !== '0') {
$value = '-' . $value;
}

$value = ltrim($digits . str_pad($decimals, 2, '0'), '0');
return $value;
}

/**
* Add one to a whole-unit digit string.
*/
protected function increment(string $whole): string
{
$chars = str_split($whole);
for($i = count($chars) - 1; $i >= 0; $i--) {
if($chars[$i] !== '9') {
$chars[$i] = (string) ((int) $chars[$i] + 1);

return implode('', $chars);
}
$chars[$i] = '0';
}

return strlen($value) ? $value : '0';
return '1' . implode('', $chars);
}

/**
Expand Down
8 changes: 8 additions & 0 deletions tests/Unit/ParsesMonetaryStringsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@
expect(Price::parse('bar 6.50', 'EUR')->__toString())->toBe('EUR 6.50');
});

it('keeps a rounded cent that carries into the next unit', function() {
expect(Price::parse('1.999', 'EUR')->__toString())->toBe('EUR 2.00');
expect(Price::parse('0.999', 'EUR')->__toString())->toBe('EUR 1.00');
expect(Price::parse('4.995', 'EUR')->__toString())->toBe('EUR 5.00');
expect(Price::parse('-1.999', 'EUR')->__toString())->toBe('EUR -2.00');
expect(Price::parse('9.996', 'EUR')->__toString())->toBe('EUR 10.00');
});

it('parses values with both narrow non-breaking and regular spaces', function() {
expect(Price::parse('1 234,56', 'EUR')->__toString())->toBe('EUR 1234.56');
expect(Price::parse('1 234,56', 'EUR')->__toString())->toBe('EUR 1234.56');
Expand Down
Loading