You could whip up your own function, because there isn’t an builtin function for this. To give you an idea:
function strtonum($string)
{
$units = [
'M' => '1000000',
'K' => '1000',
];
$unit = substr($string, -1);
if (!array_key_exists($unit, $units)) {
return 'ERROR!';
}
return (int) $string * $units[$unit];
}
Demo: http://codepad.viper-7.com/2rxbP8
Or the other way around:
function numtostring($num)
{
$units = [
'M' => '1000000',
'K' => '1000',
];
foreach ($units as $unit => $value) {
if (is_int($num / $value)) {
return $num / $value . $unit;
}
}
}
Demo: http://codepad.viper-7.com/VeRGDs
If you want to get really funky you could put all that in a class and let it decide what conversion to run:
<?php
class numberMagic
{
private $units = [];
public function __construct(array $units)
{
$this->units = $units;
}
public function parse($original)
{
if (is_numeric(substr($original, -1))) {
return $this->numToString($original);
} else {
return $this->strToNum($original);
}
}
private function strToNum($string)
{
$unit = substr($string, -1);
if (!array_key_exists($unit, $this->units)) {
return 'ERROR!';
}
return (int) $string * $this->units[$unit];
}
private function numToString($num)
{
foreach ($this->units as $unit => $value) {
if (is_int($num / $value)) {
return $num / $value . $unit;
}
}
}
}
$units = [
'M' => 1000000,
'K' => 1000,
];
$numberMagic = new NumberMagic($units);
echo $numberMagic->parse('100K'); // 100000
echo $numberMagic->parse(100); // 100K
Although this may be a bit overkill 🙂
0
solved php numbers like (10M, ..)