ฟังก์ชั่นแปลงจำนวนเงิน จากตัวเลข ให้เป็นภาษาไทย

December 22, 2007 – 11:47 pm

พอดีว่า บทความนี้น่าสนใจดี เลยเอามาลงให้อ่านกัน เพราะหลายๆ คนอาจจะเอาไปยุกต์ทำระบบอะไรได้หลายอย่างเลย เช่น ระบบขายของ พอออกไปเสร็จมา เราซื้อของไป 1500 บาท เรามาแปลงให้ตัวเลขนั้นเป็น หนึ่งพันห้าร้อยบาท ถ้วน มันก็น่าจะเท่ดีนะครับ

  1. <?php //number to thai function by Dr.Yes
  2. function num2thai($thb) {
  3. list($thb, $ths) = explode(‘.’, $thb);
  4. $ths = substr($ths.‘00′, 0, 2);
  5. $thaiNum = array(,‘หนึ่ง’,‘สอง’,‘สาม’,‘สี่’,‘ห้า′,‘หก’,‘เจ็ด’,‘แปด’,‘เก้า′);
  6. $unitBaht = array(‘บาท’,‘สิบ’,‘ร้อย’,‘พัน’,‘หมื่น’,‘แสน’,‘ล้าน’,‘สิบ’,‘ร้อย’,‘พัน’,‘หมื่น’,‘แสน’,‘ล้าน’);
  7. $unitSatang = array(‘สตางค์’,‘สิบ’);
  8. $THB = ;
  9. $j = 0;
  10. for($i=strlen($thb)-1; $i>=0; $i–,$j++) {
  11. $num = $thb[$i];
  12. $tnum = $thaiNum[$num];
  13. $unit = $unitBaht[$j];
  14. switch(true) {
  15. case $j==0 && $num==1 && strlen($thb)>1: $tnum = ‘เอ็ด’; break;
  16. case $j==1 && $num==1: $tnum = ; break;
  17. case $j==1 && $num==2: $tnum = ‘ยี่’; break;
  18. case $j==6 && $num==1 && strlen($thb)>7: $tnum = ‘เอ็ด’; break;
  19. case $j==7 && $num==1: $tnum = ; break;
  20. case $j==7 && $num==2: $tnum = ‘ยี่’; break;
  21. case $j!=0 && $j!=6 && $num==0: $unit = ; break;
  22. }
  23. $S = $tnum . $unit;
  24. $THB = $S . $THB;
  25. }
  26. if($ths==‘00′) {
  27. $THS = ‘ถ้วน’;
  28. } else {
  29. $j=0;
  30. $THS = ;
  31. for($i=strlen($ths)-1; $i>=0; $i–,$j++) {
  32. $num = $ths[$i];
  33. $tnum = $thaiNum[$num];
  34. $unit = $unitSatang[$j];
  35. switch(true) {
  36. case $j==0 && $num==1 && strlen($ths)>1: $tnum = ‘เอ็ด’; break;
  37. case $j==1 && $num==1: $tnum = ; break;
  38. case $j==1 && $num==2: $tnum = ‘ยี่’; break;
  39. case $j!=0 && $j!=6 && $num==0: $unit = ; break;
  40. }
  41. $S = $tnum . $unit;
  42. $THS = $S . $THS;
  43. }
  44. }
  45. return $THB.$THS;
  46. }
  47. $thb = mt_rand()/100; //random number;
  48. echo number_format($thb,2).“<br>”;
  49. echo num2thai($thb);
  50. ?>

ลองเอาดัดแปลงใช้ดูนะครับ เปน ฟังก์ชั่น ใช้ง่ายดี

ปล. ขอขอบคุณ Dr.Yes


Leave a reply

:mrgreen: :| :twisted: :arrow: 8O :) :? 8) :evil: :D :idea: :oops: :P :roll: ;) :cry: :o :lol: :x :( :!: :?:

  1. You will post the following soon.
    Go ahead and start typing.