php格式化数字为“1.23万”

18-11-07 16:51 字数 838 阅读 2909 已编辑

有时候直接展示一个大的数字比较不美观,就需要把数字格式化处理。比如把23000格式化为2.3万。

/**
 * @param $number
 * @return string
 */
function formatNumber($number)
{
    if (empty($number) || !is_numeric($number)) return $number;
    $unit = "";
    if ($number > 10000) {
        $leftNumber = floor($number / 10000);
        $rightNumber = round(($number % 10000) / 10000, 2);
        // $rightNumber = bcmul(($number % 10000) / 10000, '1', 2);
        $number = floatval($leftNumber + $rightNumber);
        $unit = "万";
    } else {
        $decimals = $number > 1 ? 2 : 6;
        $number = (float)number_format($number, $decimals, '.', '');
    }
    return (string)$number . $unit;
}
$number = formatNumber(0.000123);
$number1 = formatNumber(12001.00);
$number2 = formatNumber(1216111.123341);
$number3 = formatNumber(1200.00);
$number4 = formatNumber(1213.114049);
$number5 = formatNumber(20);
$number6 = formatNumber(10600.00);


var_dump($number, $number1, $number2, $number3, $number4, $number5, $number6);

结果为

'0.000123'
'1.2万'
'121.61万'
'1200'
'1213.11'
'20'
'1.06万'
4人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论