PHP演算法:如何把 00301.0050600變成正整數30100506

來源:互聯網
上載者:User

/** * @description 小數點變成正整數 * * @param $str * * @return mixed */function toIntegerNum($str){ $str = preg_replace('/(\.\d+)([0]*)/' , '\\1' , $str); $str = str_replace('.' , '' , $str); return $str;}$s = 00301.0050600;var_dump(toIntegerNum($s)); //輸出string '30100506' (length=8)

新修改

重新改寫了一下,還有更好的方法嗎

/** * @description 小數點變成正整數 * * @param $str * * @return mixed */function toIntegerNum($str){    $arr = explode('.' , $str);    if (!empty($arr[0])) {        $arr[0] = ltrim($arr[0] , '0');    }    if (!empty($arr[1])) {        $arr[1] = rtrim($arr[1] , '0');    }    return ltrim(implode('' , $arr),'0');}$s = '00301.0050600';//$s = 00301.0050600;//$s = 300;$s = 0.00560000;var_dump(toIntegerNum($s));

回複內容:


/** * @description 小數點變成正整數 * * @param $str * * @return mixed */function toIntegerNum($str){ $str = preg_replace('/(\.\d+)([0]*)/' , '\\1' , $str); $str = str_replace('.' , '' , $str); return $str;}$s = 00301.0050600;var_dump(toIntegerNum($s)); //輸出string '30100506' (length=8)

新修改

重新改寫了一下,還有更好的方法嗎

/** * @description 小數點變成正整數 * * @param $str * * @return mixed */function toIntegerNum($str){    $arr = explode('.' , $str);    if (!empty($arr[0])) {        $arr[0] = ltrim($arr[0] , '0');    }    if (!empty($arr[1])) {        $arr[1] = rtrim($arr[1] , '0');    }    return ltrim(implode('' , $arr),'0');}$s = '00301.0050600';//$s = 00301.0050600;//$s = 300;$s = 0.00560000;var_dump(toIntegerNum($s));

按狀態來解析:

  1. 記錄整數部分頭部零:
    從前往後逐位解析一遍,記錄頭部零的位元,直到遇到非零值或結尾;
  2. 記錄小數部分尾部零:
    如果有小數點,則從後往前逐位解析一遍,記錄尾部零的位元,直到遇到非零值或小數點;
  3. 把頭部零和尾部0全部刨除,最後去掉小數點。

LZ已經給出答案了啊=w=

return trim(str_replace('.','',$str),'0')

借 @tczzjin 的答案

$str = 00301.0050600;echo intval(str_replace('.','',$str));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.