【问题标题】:Convert Thousands in K format to regular Thousands format将 K 格式的千位转换为常规的千位格式
【发布时间】:2018-06-18 08:16:52
【问题描述】:

我收到了以下格式的号码:

12.2K

我想将此数字转换为显示:

12200

examples ive seen 转换为 K 格式,但我想从 K 格式转换。

有没有简单的方法可以做到这一点?

谢谢!

【问题讨论】:

  • 这不是代码编写服务。一旦你有了一些代码,就问一个更具体的问题。

标签: php number-formatting


【解决方案1】:

你的意思是,像这样的东西?这将能够转换成千上万,等等。

<?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);
  }
?>

【讨论】:

    【解决方案2】:
    <?php
    $number = '12.2K';
    
    if (strpos($number, 'K') !== false)
        {
        $number = rtrim($number, 'K') * 1000;
        }
    
    echo $number
    ?>
    

    基本上,您只是想检查字符串是否包含某个字符,如果包含,则通过将其取出并将其乘以 1000 来响应它。

    【讨论】:

      【解决方案3】:

      另一种方法是将缩写放在一个数组中,并使用 的幂来计算要相乘的数字。
      如果您有很多缩写,这会给出更短的代码。
      我使用 strtoupper 来确保它同时匹配 kK

      $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
      }
      

      https://3v4l.org/LXVXN

      【讨论】:

        【解决方案4】:
        $result = str_ireplace(['.', 'K'], ['', '00'], '12.2K');
        

        你也可以用其他字母等来扩展它。

        【讨论】:

        • 当输入为12k时,那么呢?
        猜你喜欢
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多