diff --git a/src/Formatters/QuantityFormatter.php b/src/Formatters/QuantityFormatter.php index f4c9153..59bf475 100644 --- a/src/Formatters/QuantityFormatter.php +++ b/src/Formatters/QuantityFormatter.php @@ -26,8 +26,22 @@ class QuantityFormatter implements IFormatter public static function format($value) { $value = Utils::toString($value); - $bn = Utils::toBn($value); - return '0x' . $bn->toHex(true); + if (Utils::isZeroPrefixed($value)) { + // test hex with zero ahead, hardcode 0x0 + if ($value === '0x0' || strpos($value, '0x0') !== 0) { + return $value; + } + $hex = preg_replace('/^0x0+(?!$)/', '', $value); + } else { + $bn = Utils::toBn($value); + $hex = $bn->toHex(true); + } + if (empty($hex)) { + $hex = '0'; + } else { + $hex = preg_replace('/^0+(?!$)/', '', $hex); + } + return '0x' . $hex; } } \ No newline at end of file diff --git a/test/unit/QuantityFormatterTest.php b/test/unit/QuantityFormatterTest.php new file mode 100644 index 0000000..c098f8b --- /dev/null +++ b/test/unit/QuantityFormatterTest.php @@ -0,0 +1,55 @@ +formatter = new QuantityFormatter; + } + + /** + * testFormat + * + * @return void + */ + public function testFormat() + { + $formatter = $this->formatter; + + $this->assertEquals('0x927c0', $formatter->format(0x0927c0)); + $this->assertEquals('0x927c0', $formatter->format('0x0927c0')); + $this->assertEquals('0x927c0', $formatter->format('0x927c0')); + $this->assertEquals('0x927c0', $formatter->format('600000')); + $this->assertEquals('0x927c0', $formatter->format(600000)); + + $this->assertEquals('0xea60', $formatter->format('0x0ea60')); + $this->assertEquals('0xea60', $formatter->format('0xea60')); + $this->assertEquals('0xea60', $formatter->format(0x0ea60)); + $this->assertEquals('0xea60', $formatter->format('60000')); + $this->assertEquals('0xea60', $formatter->format(60000)); + + $this->assertEquals('0x0', $formatter->format(0x00)); + $this->assertEquals('0x0', $formatter->format('0x00')); + $this->assertEquals('0x0', $formatter->format('0x0')); + $this->assertEquals('0x0', $formatter->format('0')); + $this->assertEquals('0x0', $formatter->format(0)); + } +} \ No newline at end of file