当前位置:Gxlcms > PHP教程 > php实现大数以,作分隔符分隔的代码

php实现大数以,作分隔符分隔的代码

时间:2021-07-01 10:21:17 帮助过:6人阅读

  1. //未考虑浮点型
  2. /*
  3. * method 1
  4. * echo number_format($str,2,'.',',');
  5. */
  6. /* method2
  7. * 先反转字符串strrev 再str_split($str,3);
  8. $str = strrev($str);
  9. $arr = str_split($str,3);//987
  10. $res = '';
  11. $count = count($arr);
  12. while($count--){
  13. $res .= strrev($arr[$count]).',';
  14. }
  15. $res = rtrim($res,',');
  16. */
  17. /* method 3
  18. * 截取出每3个字符
  19. * $count = strlen($str);
  20. $i = 0;
  21. $md = $count % 3;
  22. switch ($md){
  23. case 0:
  24. break;
  25. case 1:
  26. $res = $str{0}.',';
  27. $count -=1;
  28. $i = 1;
  29. break;
  30. case 2:
  31. $res = substr($str,0,2).',';
  32. $count -= 2;
  33. $i = 2;
  34. break;
  35. }
  36. for(;$i<$count-3;$i+=3){
  37. $res .= substr($str,$i,3).',';
  38. }
  39. $res .= substr($str,$i,3);
  40. */
  41. /* method 4
  42. * 正则,求不确定长度的做法
  43. $md = strlen($str) % 3;
  44. $res = substr($str, 0,$md).($md == 0?'':',');
  45. $res .= preg_replace('(\d{3})', '\\0,', substr($str, $md));
  46. $res = rtrim($res,',');
  47. */
  48. ?>

人气教程排行