【发布时间】:2018-06-18 08:16:52
【问题描述】:
【问题讨论】:
-
这不是代码编写服务。一旦你有了一些代码,就问一个更具体的问题。
标签: php number-formatting
【问题讨论】:
标签: php number-formatting
你的意思是,像这样的东西?这将能够转换成千上万,等等。
<?php
$s = "12.2K";
if (strpos(strtoupper($s), "K") != false) {
$s = rtrim($s, "kK");
echo floatval($s) * 1000;
} else if (strpos(strtoupper($s), "M") != false) {
$s = rtrim($s, "mM");
echo floatval($s) * 1000000;
} else {
echo floatval($s);
}
?>
【讨论】:
<?php
$number = '12.2K';
if (strpos($number, 'K') !== false)
{
$number = rtrim($number, 'K') * 1000;
}
echo $number
?>
基本上,您只是想检查字符串是否包含某个字符,如果包含,则通过将其取出并将其乘以 1000 来响应它。
【讨论】:
另一种方法是将缩写放在一个数组中,并使用 的幂来计算要相乘的数字。
如果您有很多缩写,这会给出更短的代码。
我使用 strtoupper 来确保它同时匹配 k 和 K。
$arr = ["K" => 1 ,"M" => 2, "T" => 3]; // and so on for how ever long you need
$input = "12.2K";
if(isset($arr[strtoupper(substr($input, -1))])){ //does the last character exist in array as an key
echo substr($input,0,-1) * pow(1000, $arr[strtoupper(substr($input, -1))]); //multiply with the power of the value in array
// 12.2 * 1000^1
}else{
echo $input; // less than 1k, just output
}
【讨论】:
$result = str_ireplace(['.', 'K'], ['', '00'], '12.2K');
你也可以用其他字母等来扩展它。
【讨论】: