Fix 53
toWei support fraction/float number.
This commit is contained in:
parent
b10680cddb
commit
507b1d89e6
@ -282,6 +282,25 @@ class Utils
|
||||
}
|
||||
$bnt = new BigNumber(self::UNITS[$unit]);
|
||||
|
||||
if (is_array($bn)) {
|
||||
// fraction number
|
||||
list($whole, $fraction, $negative1) = $bn;
|
||||
|
||||
$fractionLength = strlen($fraction->toString());
|
||||
|
||||
if ($fractionLength > strlen(self::UNITS[$unit])) {
|
||||
throw new InvalidArgumentException('toWei fraction part is out of limit.');
|
||||
}
|
||||
$whole = $whole->multiply($bnt);
|
||||
$base = (new BigNumber(10))->pow(new BigNumber($fractionLength));
|
||||
$fraction = $fraction->multiply($bnt)->divide($base)[0];
|
||||
|
||||
if ($negative1 !== false) {
|
||||
return $whole->add($fraction)->multiply($negative1);
|
||||
}
|
||||
return $whole->add($fraction);
|
||||
}
|
||||
|
||||
return $bn->multiply($bnt);
|
||||
}
|
||||
|
||||
|
@ -259,14 +259,51 @@ class UtilsTest extends TestCase
|
||||
$bn = Utils::toWei('0x5218', 'wei');
|
||||
$this->assertEquals($bn->toString(), '21016');
|
||||
|
||||
$bn = Utils::toWei('0.1', 'ether');
|
||||
$this->assertEquals($bn->toString(), '100000000000000000');
|
||||
|
||||
$bn = Utils::toWei('1.69', 'ether');
|
||||
$this->assertEquals($bn->toString(), '1690000000000000000');
|
||||
|
||||
$bn = Utils::toWei(0.1, 'ether');
|
||||
$this->assertEquals($bn->toString(), '100000000000000000');
|
||||
|
||||
$bn = Utils::toWei(1.69, 'ether');
|
||||
$this->assertEquals($bn->toString(), '1690000000000000000');
|
||||
|
||||
$bn = Utils::toWei('-0.1', 'ether');
|
||||
$this->assertEquals($bn->toString(), '-100000000000000000');
|
||||
|
||||
$bn = Utils::toWei('-1.69', 'ether');
|
||||
$this->assertEquals($bn->toString(), '-1690000000000000000');
|
||||
|
||||
$bn = Utils::toWei(-0.1, 'ether');
|
||||
$this->assertEquals($bn->toString(), '-100000000000000000');
|
||||
|
||||
$bn = Utils::toWei(-1.69, 'ether');
|
||||
$this->assertEquals($bn->toString(), '-1690000000000000000');
|
||||
|
||||
$bn = Utils::toWei('', 'ether');
|
||||
$this->assertEquals($bn->toString(), '0');
|
||||
|
||||
$bn = Utils::toWei(-1.697, 'kwei');
|
||||
$this->assertEquals($bn->toString(), '-1697');
|
||||
|
||||
try {
|
||||
$toWei = Utils::toWei('0x5218', new stdClass);
|
||||
$bn = Utils::toWei('0x5218', new stdClass);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->assertTrue($e !== null);
|
||||
}
|
||||
|
||||
try {
|
||||
$toWei = Utils::toWei('0x5218', 'test');
|
||||
$bn = Utils::toWei('0x5218', 'test');
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->assertTrue($e !== null);
|
||||
}
|
||||
|
||||
try {
|
||||
// out of limit
|
||||
$bn = Utils::toWei(-1.6977, 'kwei');
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->assertTrue($e !== null);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user