vlc*_*mi3 -3 php number-formatting
我想使用10M(代表1000000)和100K等数字。PHP中是否已经存在一个函数,还是我必须编写自己的函数?
我在想一些类似的事情:
echo strtonum("100K"); // prints 100000
Run Code Online (Sandbox Code Playgroud)
另外,再往前走一步,反过来,要翻译一下,从100000中得到10万吗?
您可以使用自己的函数,因为没有内置函数。给您一个想法:
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];
}
Run Code Online (Sandbox Code Playgroud)
演示:http://codepad.viper-7.com/2rxbP8
或反过来:
function numtostring($num)
{
$units = [
'M' => '1000000',
'K' => '1000',
];
foreach ($units as $unit => $value) {
if (is_int($num / $value)) {
return $num / $value . $unit;
}
}
}
Run Code Online (Sandbox Code Playgroud)
演示:http://codepad.viper-7.com/VeRGDs
如果您想变得非常时髦,可以将所有内容放在一个类中,然后让它决定要运行的转换:
<?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
Run Code Online (Sandbox Code Playgroud)
虽然这可能有点矫kill过正:)
演示:http://codepad.viper-7.com/KZEc7b