Hỏi về thuật toán
-
Chào các bác, em có 1 bài toán như sau
Đổi những số quá dài thành K (trăm ngàn), M (triệu), B(tỷ). Em có 1 thuật toán như sauif( ! function_exists('mJobStrAmount')) { function mJobStrAmount() { return $str_amount = array( 0 => '', 1 => 'K', 2 => 'M', 3 => 'B', 4 => 'T' ); } } if( ! function_exists('mJobShortCurrent')) { function mJobShortCurrent($amount,$decimal = 2) { // strip any formatting and convert to interger $amount = (0 + str_replace(",","",$amount)); // check is this a number if(!is_numeric($amount)) return false; $str_amount = mJobStrAmount(); if($amount >=1000000000000) $result = array( 'n_amount' => round(($amount/1000000000000),$decimal), 'str_amount' => $str_amount[4], ); else if($amount>=1000000000) $result = array( 'n_amount' => round(($amount/1000000000),$decimal), 'str_amount' => $str_amount[3], ); else if($amount>=1000000) $result = array( 'n_amount' => round(($amount/1000000),$decimal), 'str_amount' => $str_amount[2], ); else if($amount>=1000) $result = array( 'n_amount' => round(($amount/1000),$decimal), 'str_amount' => $str_amount[1], ); else $result = array( 'n_amount' => round($amount,$decimal), 'str_amount' => $str_amount[0], ); return $result; } }
trong đó em dùng phép chia để rút gọn các số lại và tương ứng nó sẽ nhận giá trị K, M, B tương ứng.
Nhưng thuật toán này em nghỉ chưa tối ưu lắm. Có bác nào có thuật toán tối ưu hơn không ạ.
Trân trọng cảm ơn
-
Không biết Php đâu, Javascript thì nó vậy là chạy được
var convert = function(num){ var arrV = [1E9,1E6,1E3], arrS = ['B','M','K'], result = num; arrV.forEach(function(item,index){ if (num < item) return; var value = Math.ceil(num/item); if (value<1000 && value >=1) { result = arrS[index]; }; }); return result; };