php-decimal / ext-decimal

Correctly-rounded, arbitrary precision decimal floating-point arithmetic in PHP
https://php-decimal.github.io/
MIT License
338 stars 19 forks source link

Consider adding support for packed BCD #26

Open rybakit opened 5 years ago

rybakit commented 5 years ago

Hi! I work on a msgpack extension that can pack/unpack fixed-point decimals that are stored in the following format:

+-------+--------------------------------+
| scale | packed BCD (2 digits per byte) |
+-------+--------------------------------+

I implemented packing/unpacking logic in pure PHP, but wonder if it would make sense to add support of packed decimals to this extension. Wdyt?

For example, here is how I pack them now:

$data = $value->toFixed(self::PRECISION);

if ('-' === $data[0]) {
    $nibble = 'd';
    $data = \substr($data, 1);
} else {
    $nibble = 'c';
}

$pieces = \explode('.', $data, 2);
$pieces[1] = \rtrim($pieces[1], '0');

$data = "{$pieces[0]}{$pieces[1]}{$nibble}";
if (0 !== \strlen($data) % 2) {
    $data = '0'.$data;
}

$scale = empty($pieces[1]) ? 0 : \strlen($pieces[1]);

return [$scale, \hex2bin($data)];
rtheunissen commented 4 years ago

How does this compare or relate to how mpdecimal stores decimal values?

rybakit commented 3 years ago

I'm not familiar with mpdecimal and don't know how it stores decimals, but if I'm not mistaken, this is implemented in the decNumber library. Maybe this link will explain better what I need:

And some more links to the implementation: