将1345转换为1.3k,依此类推

时间:2014-02-03 21:06:49

标签: php

我正在寻找一种方法将1000以上的任何值改为1位小数。

所以,例如900保持900,但1345变为1.3,然后我将添加尾随K。

它永远不会变成数百万,所以我不必担心检查尾随的信。

但我不确定如何添加小数位?

3 个答案:

答案 0 :(得分:5)

这样的东西?

function round_thousands($number){
    if($number < 1000){
        return $number;
    } else {
        return number_format($number/1000, 1).'K';
    }
}

答案 1 :(得分:1)

更精细的K,M和B版本

function format_num($num, $precision = 2) {
    if ($num >= 1000 && $num < 1000000) {
        $n_format = number_format($num/1000,$precision).'K';
    } else if ($num >= 1000000 && $num < 1000000000) {
        $n_format = number_format($num/1000000,$precision).'M';
    } else if ($num >= 1000000000) {
        $n_format=number_format($num/1000000000,$precision).'B';
    } else {
        $n_format = $num;
    }
    return $n_format;
} 

答案 2 :(得分:1)

我创建了一个类来封装这个逻辑:

interface Quantifier {
    public function quantify($input);
}

class NumberQuantifier implements Quantifier {
    protected $quantifierList;

    public function __construct($quantifierList) {
        $this->quantifierList = $quantifierList;
        arsort($this->quantifierList); //Make sure they are largest too smallest.
    }

    public function quantify($number) {
        foreach ($this->quantifierList as $symbol => $threshold) {
            if ($threshold > $number) continue;

            return number_format($number / $threshold, 1) . $symbol;
        }
    }
}

创建此类的实例时,您可以传递一个量词列表:

$numberQuantifier = new NumberQuantifier(array(
    'B' => 1000000000,
    'M' => 1000000,
    'K' => 1000
));

然后您可以像这样使用它:

echo $numberQuantifier->quantify(148293);
echo $numberQuantifier->quantify(2356458);
echo $numberQuantifier->quantify(23568534);
echo $numberQuantifier->quantify(8927492842);

输出(添加换行符):

148.3K
2.4M
23.6M
8.9B

See it here


现在,想象一下你想要量化除了数字之外的其他东西。以下是一些例子:

文件大小

$fileSizeQuantifier = new NumberQuantifier(array(
    'TB' => 1099511627776,
    'GB' => 1073741824,
    'MB' => 1048576,
    'KB' => 1024
));

质谱

考虑一个您可能需要多个量词类型的示例:

$metricMassQuantifier = new NumberQuantifier(array(
    'Mg'  => 1000000,    //megagram
    'kg'  => 1000,       //kilogram
    'hg'  => 100,        //hectogram
    'dag' => 10,         //decagram
    'g'   => 1,          //gram
    'dg'  => 1/10,       //decigram
    'cg'  => 1/100,      //centigram
    'mg'  => 1/1000,     //millgram
    'mcg' => 1/10000000  //microgram
));

$imperialMassQuantifier = new NumberQuantifier(array(
    'gr'  => 1/7000, //grain
    'dr'  => 1/256,  //drachm
    'oz'  => 1/16,   //ounce
    'lb'  => 1,      //pound
    'st'  => 14,     //stone
    'qtr' => 28,     //quarter
    'cwt' => 112,    //hundredweight
    't'   => 2240    //ton
));

echo "Metric: {$metricMassQuantifier->quantify(456)} \r\n";
echo "Imperial: {$imperialMassQuantifier->quantify(456)} \r\n";

输出

Metric: 4.6hg 
Imperial: 4.1cwt 

See this demo