Kotchasan Framework Documentation

Kotchasan Framework Documentation

คลาส Currency - การจัดการสกุลเงินและตัวเลข

TH 03 Feb 2026 13:19

คลาส Currency - การจัดการสกุลเงินและตัวเลข

คลาส Currency เป็นยูทิลิตี้สำหรับแปลงตัวเลขเป็นคำอ่านภาษาไทยและอังกฤษ, คำนวณภาษีมูลค่าเพิ่ม (VAT), และจัดรูปแบบตัวเลขทางการเงิน

Namespace

Kotchasan\Currency

ภาพรวม

Currency class มีฟังก์ชันหลัก:

  • แปลงตัวเลขเป็นคำอ่านภาษาไทย (บาท/สตางค์)
  • แปลงตัวเลขเป็นคำอ่านภาษาอังกฤษ (baht/satang)
  • คำนวณค่า VAT ทั้งแบบรวมและไม่รวม VAT
  • จัดรูปแบบตัวเลขด้วยทศนิยมและตัวคั่นหลักพัน

API Reference

bahtThai()

แปลงตัวเลขเป็นคำอ่านภาษาไทย (บาท)

public static function bahtThai($thb): string

Parameters:

  • $thb - จำนวนเงิน (float, int, หรือ string)

Returns: คำอ่านภาษาไทย เช่น "หนึ่งร้อยบาทถ้วน", "สองพันบาทห้าสิบสตางค์"

Example:

use Kotchasan\Currency;

// ตัวเลขพื้นฐาน
echo Currency::bahtThai(13);
// "สิบสามบาทถ้วน"

echo Currency::bahtThai(101.55);
// "หนึ่งร้อยเอ็ดบาทห้าสิบห้าสตางค์"

echo Currency::bahtThai(1234.56);
// "หนึ่งพันสองร้อยสามสิบสี่บาทห้าสิบหกสตางค์"

// จำนวนใหญ่
echo Currency::bahtThai(1000000);
// "หนึ่งล้านบาทถ้วน"

echo Currency::bahtThai(10000000050.25);
// "หนึ่งหมื่นล้านห้าสิบบาทยี่สิบห้าสตางค์"

// จำนวนติดลบ
echo Currency::bahtThai(-1000000050);
// "ลบหนึ่งพันล้านห้าสิบบาทถ้วน"

// ใช้ในใบเสร็จ
class Receipt
{
    public function generate($total)
    {
        echo "ยอดรวม: " . number_format($total, 2) . " บาท\n";
        echo "(" . Currency::bahtThai($total) . ")\n";
    }
}

$receipt = new Receipt();
$receipt->generate(1500.75);
// ยอดรวม: 1,500.75 บาท
// (หนึ่งพันห้าร้อยบาทเจ็ดสิบห้าสตางค์)

// ใบสำคัญจ่าย
function createPaymentVoucher($amount, $payee)
{
    $text = "จ่ายเงินให้: {$payee}\n";
    $text .= "จำนวนเงิน: " . Currency::bahtThai($amount) . "\n";
    $text .= "(" . number_format($amount, 2) . " บาท)";
    return $text;
}

echo createPaymentVoucher(25000, "บริษัท ABC จำกัด");

bahtEng()

แปลงตัวเลขเป็นคำอ่านภาษาอังกฤษ (baht)

public static function bahtEng($thb): string

Parameters:

  • $thb - จำนวนเงิน (float, int, หรือ string)

Returns: คำอ่านภาษาอังกฤษ เช่น "one hundred baht", "two thousand baht and fifty satang"

Example:

use Kotchasan\Currency;

// ตัวเลขพื้นฐาน
echo Currency::bahtEng(13);
// "thirteen baht"

echo Currency::bahtEng(101.55);
// "one hundred one baht and fifty-five satang"

echo Currency::bahtEng(1234.56);
// "one thousand two hundred thirty-four baht and fifty-six satang"

// จำนวนใหญ่
echo Currency::bahtEng(1000000);
// "one million baht"

// จำนวนติดลบ
echo Currency::bahtEng(-500);
// "negative five hundred baht"

// เช็คธนาคาร
class BankCheck
{
    public function create($amount, $payee, $date)
    {
        $check = "Pay to: {$payee}\n";
        $check .= "Amount: " . number_format($amount, 2) . " THB\n";
        $check .= "Amount in words: " . Currency::bahtEng($amount) . "\n";
        $check .= "Date: {$date}\n";
        return $check;
    }
}

$check = new BankCheck();
echo $check->create(15750.50, "John Smith", "2024-01-15");
// Pay to: John Smith
// Amount: 15,750.50 THB
// Amount in words: fifteen thousand seven hundred fifty baht and fifty satang
// Date: 2024-01-15

// ใบแจ้งหนี้นานาชาติ
function createInternationalInvoice($items, $customer)
{
    $total = array_sum(array_column($items, 'amount'));

    $invoice = "INVOICE\n";
    $invoice .= "Customer: {$customer}\n\n";

    foreach ($items as $item) {
        $invoice .= "- {$item['desc']}: " . number_format($item['amount'], 2) . " THB\n";
    }

    $invoice .= "\nTotal: " . number_format($total, 2) . " THB\n";
    $invoice .= "(" . Currency::bahtEng($total) . ")";

    return $invoice;
}

calcVat()

คำนวณค่า VAT จากจำนวนเงิน

public static function calcVat(float $amount, float $vat, bool $vat_ex = true): float

Parameters:

  • $amount - จำนวนเงิน
  • $vat - อัตรา VAT (เปอร์เซ็นต์) เช่น 7
  • $vat_ex - true = ไม่รวม VAT (exclusive), false = รวม VAT แล้ว (inclusive)

Returns: ค่า VAT

VAT Exclusive (ยอดไม่รวม VAT):

VAT = (amount × vat) ÷ 100

VAT Inclusive (ยอดรวม VAT แล้ว):

VAT = amount - (amount × 100 ÷ (100 + vat))

Example:

use Kotchasan\Currency;

// VAT 7% จากยอดไม่รวม VAT (exclusive)
$vat = Currency::calcVat(1000, 7, true);
echo $vat; // 70

$grandTotal = 1000 + $vat; // 1070

// VAT จากยอดรวม VAT แล้ว (inclusive)
$vat = Currency::calcVat(1070, 7, false);
echo number_format($vat, 2); // 70.00

$netAmount = 1070 - $vat; // 1000

// ระบบคำนวณใบแจ้งหนี้
class InvoiceCalculator
{
    private $vatRate;

    public function __construct($vatRate = 7)
    {
        $this->vatRate = $vatRate;
    }

    public function calculate($items)
    {
        $subtotal = 0;
        foreach ($items as $item) {
            $subtotal += $item['price'] * $item['qty'];
        }

        $vat = Currency::calcVat($subtotal, $this->vatRate, true);
        $total = $subtotal + $vat;

        return [
            'subtotal' => $subtotal,
            'vat' => $vat,
            'total' => $total
        ];
    }

    public function reverseCalculate($totalWithVat)
    {
        $vat = Currency::calcVat($totalWithVat, $this->vatRate, false);
        $subtotal = $totalWithVat - $vat;

        return [
            'subtotal' => $subtotal,
            'vat' => $vat,
            'total' => $totalWithVat
        ];
    }
}

$calc = new InvoiceCalculator(7);

// คำนวณจากยอดไม่รวม VAT
$items = [
    ['name' => 'สินค้า A', 'price' => 500, 'qty' => 2],
    ['name' => 'สินค้า B', 'price' => 300, 'qty' => 1]
];

$result = $calc->calculate($items);
echo "ยอดรวม: " . number_format($result['subtotal'], 2) . " บาท\n";
echo "VAT 7%: " . number_format($result['vat'], 2) . " บาท\n";
echo "รวมทั้งสิ้น: " . number_format($result['total'], 2) . " บาท\n";
// ยอดรวม: 1,300.00 บาท
// VAT 7%: 91.00 บาท
// รวมทั้งสิ้น: 1,391.00 บาท

// แยก VAT จากยอดรวม
$reverse = $calc->reverseCalculate(1391);
echo "ยอดก่อน VAT: " . number_format($reverse['subtotal'], 2) . " บาท\n";
echo "VAT: " . number_format($reverse['vat'], 2) . " บาท\n";
// ยอดก่อน VAT: 1,300.00 บาท
// VAT: 91.00 บาท

// POS System
class POSSystem
{
    public function processTransaction($items, $discount = 0, $vatRate = 7)
    {
        // คำนวณยอดรวม
        $subtotal = 0;
        foreach ($items as $item) {
            $subtotal += $item['price'] * $item['qty'];
        }

        // หักส่วนลด
        $discountAmount = ($subtotal * $discount) / 100;
        $afterDiscount = $subtotal - $discountAmount;

        // คำนวณ VAT
        $vat = Currency::calcVat($afterDiscount, $vatRate, true);
        $total = $afterDiscount + $vat;

        return [
            'subtotal' => $subtotal,
            'discount_percent' => $discount,
            'discount_amount' => $discountAmount,
            'after_discount' => $afterDiscount,
            'vat' => $vat,
            'total' => $total,
            'total_thai' => Currency::bahtThai($total)
        ];
    }
}

$pos = new POSSystem();
$transaction = $pos->processTransaction([
    ['name' => 'สินค้า 1', 'price' => 1000, 'qty' => 2],
    ['name' => 'สินค้า 2', 'price' => 500, 'qty' => 1]
], 10, 7); // ส่วนลด 10%, VAT 7%

echo "ยอดรวม: " . number_format($transaction['subtotal'], 2) . " บาท\n";
echo "ส่วนลด 10%: " . number_format($transaction['discount_amount'], 2) . " บาท\n";
echo "หลังหักส่วนลด: " . number_format($transaction['after_discount'], 2) . " บาท\n";
echo "VAT 7%: " . number_format($transaction['vat'], 2) . " บาท\n";
echo "ชำระทั้งสิ้น: " . number_format($transaction['total'], 2) . " บาท\n";
echo "(" . $transaction['total_thai'] . ")\n";

format()

จัดรูปแบบตัวเลขด้วยทศนิยมและตัวคั่นหลักพัน

public static function format(
    float $amount,
    int $digit = 2,
    string $thousands_sep = ',',
    bool $round = true
): string

Parameters:

  • $amount - ตัวเลขที่ต้องการจัดรูปแบบ
  • $digit - จำนวนหลักทศนิยม (default: 2)
  • $thousands_sep - ตัวคั่นหลักพัน (default: ',')
  • $round - ปัดเศษ (default: true)

Returns: ตัวเลขที่จัดรูปแบบแล้ว

Rounding Behavior:

  • $round = true: ปัดเศษตามหลักทศนิยมที่กำหนด
  • $round = false: ตัดทศนิยมเกิน ไม่ปัดเศษ

Example:

use Kotchasan\Currency;

// พื้นฐาน (2 ทศนิยม, ปัดเศษ)
echo Currency::format(1000000.444);
// "1,000,000.44"

echo Currency::format(1000000.555);
// "1,000,000.56" (ปัดขึ้น)

// ทศนิยม 3 ตำแหน่ง, ไม่ปัดเศษ
echo Currency::format(1000000.55455, 3, ',', false);
// "1,000,000.554" (ตัดทิ้ง)

// ทศนิยม 3 ตำแหน่ง, ปัดเศษ
echo Currency::format(1000000.55455, 3);
// "1,000,000.555" (ปัดขึ้น)

// ไม่มีตัวคั่น
echo Currency::format(1234.56, 2, '');
// "1234.56"

// ใช้จุดเป็นตัวคั่นหลักพัน
echo Currency::format(1234567.89, 2, '.');
// "1.234.567.89"

// ตัวคั่นแบบ space
echo Currency::format(9999999.99, 2, ' ');
// "9 999 999.99"

// รายงานการเงิน
class FinancialReport
{
    public function generate($data)
    {
        $report = "รายงานการเงิน\n";
        $report .= str_repeat("=", 50) . "\n\n";

        $totalIncome = 0;
        $totalExpense = 0;

        $report .= "รายได้:\n";
        foreach ($data['income'] as $item) {
            $totalIncome += $item['amount'];
            $report .= "  {$item['desc']}: " .
                      Currency::format($item['amount']) . " บาท\n";
        }

        $report .= "\nรายจ่าย:\n";
        foreach ($data['expenses'] as $item) {
            $totalExpense += $item['amount'];
            $report .= "  {$item['desc']}: " .
                      Currency::format($item['amount']) . " บาท\n";
        }

        $netIncome = $totalIncome - $totalExpense;

        $report .= "\n" . str_repeat("-", 50) . "\n";
        $report .= "รวมรายได้: " . Currency::format($totalIncome) . " บาท\n";
        $report .= "รวมรายจ่าย: " . Currency::format($totalExpense) . " บาท\n";
        $report .= "กำไร/ขาดทุน: " . Currency::format($netIncome) . " บาท\n";

        return $report;
    }
}

// ตารางราคา
class PriceTable
{
    public function create($products)
    {
        $table = sprintf("%-30s %15s\n", "สินค้า", "ราคา");
        $table .= str_repeat("-", 50) . "\n";

        foreach ($products as $product) {
            $price = Currency::format($product['price']);
            $table .= sprintf("%-30s %15s\n",
                            $product['name'],
                            $price . ' บาท');
        }

        return $table;
    }
}

$priceTable = new PriceTable();
echo $priceTable->create([
    ['name' => 'Laptop', 'price' => 25000.50],
    ['name' => 'Mouse', 'price' => 350.75],
    ['name' => 'Keyboard', 'price' => 1200]
]);

// แสดงราคาหลายสกุลเงิน
function formatPrice($amount, $currency = 'THB', $precision = 2)
{
    $formatted = Currency::format($amount, $precision);

    switch ($currency) {
        case 'USD':
            return '$' . $formatted;
        case 'EUR':
            return '€' . $formatted;
        case 'THB':
        default:
            return $formatted . ' บาท';
    }
}

echo formatPrice(1500.75, 'USD'); // $1,500.75
echo formatPrice(1500.75, 'THB'); // 1,500.75 บาท

// การปัดเศษพิเศษสำหรับราคาน้ำมัน (3 ทศนิยม)
$oilPrice = 35.754;
echo "ราคาน้ำมัน: " . Currency::format($oilPrice, 3) . " บาท/ลิตร";
// "ราคาน้ำมัน: 35.754 บาท/ลิตร"

ตัวอย่างการใช้งานจริง

1. ระบบใบเสร็จแบบครบวงจร

use Kotchasan\Currency;

class ReceiptSystem
{
    public function generate($items, $vatRate = 7)
    {
        $receipt = "ใบเสร็จรับเงิน\n";
        $receipt .= str_repeat("=", 60) . "\n\n";

        $subtotal = 0;
        $receipt .= sprintf("%-30s %8s %10s %12s\n",
                          "สินค้า", "จำนวน", "ราคา", "รวม");
        $receipt .= str_repeat("-", 60) . "\n";

        foreach ($items as $item) {
            $itemTotal = $item['price'] * $item['qty'];
            $subtotal += $itemTotal;

            $receipt .= sprintf("%-30s %8d %10s %12s\n",
                              $item['name'],
                              $item['qty'],
                              Currency::format($item['price']),
                              Currency::format($itemTotal));
        }

        $vat = Currency::calcVat($subtotal, $vatRate, true);
        $total = $subtotal + $vat;

        $receipt .= str_repeat("-", 60) . "\n";
        $receipt .= sprintf("%51s %12s\n", "ยอดรวม:",
                          Currency::format($subtotal) . " บาท");
        $receipt .= sprintf("%51s %12s\n", "VAT {$vatRate}%:",
                          Currency::format($vat) . " บาท");
        $receipt .= sprintf("%51s %12s\n", "รวมทั้งสิ้น:",
                          Currency::format($total) . " บาท");
        $receipt .= "\n(" . Currency::bahtThai($total) . ")\n";

        return $receipt;
    }
}

2. ระบบเงินเดือน

class PayrollSystem
{
    public function generatePayslip($employee, $salary, $deductions = [])
    {
        $slip = "ใบจ่ายเงินเดือน\n";
        $slip .= "ชื่อ: {$employee['name']}\n";
        $slip .= "ตำแหน่ง: {$employee['position']}\n\n";

        $slip .= "เงินเดือน: " . Currency::format($salary) . " บาท\n";

        if (!empty($deductions)) {
            $slip .= "\nรายการหัก:\n";
            $totalDeduction = 0;

            foreach ($deductions as $type => $amount) {
                $totalDeduction += $amount;
                $slip .= "  {$type}: " . Currency::format($amount) . " บาท\n";
            }

            $slip .= "  รวมหัก: " . Currency::format($totalDeduction) . " บาท\n";

            $netSalary = $salary - $totalDeduction;
        } else {
            $netSalary = $salary;
        }

        $slip .= "\nเงินสุทธิ: " . Currency::format($netSalary) . " บาท\n";
        $slip .= "(" . Currency::bahtThai($netSalary) . ")\n";

        return $slip;
    }
}

$payroll = new PayrollSystem();
echo $payroll->generatePayslip(
    ['name' => 'สมชาย ใจดี', 'position' => 'Developer'],
    35000,
    ['ประกันสังคม' => 750, 'ภาษี' => 2500]
);

3. ระบบใบกำกับภาษี

class TaxInvoice
{
    public function create($invoiceData)
    {
        $doc = "ใบกำกับภาษี/ใบเสร็จรับเงิน\n";
        $doc .= "เลขที่: {$invoiceData['number']}\n";
        $doc .= "ลูกค้า: {$invoiceData['customer']}\n";
        $doc .= "วันที่: {$invoiceData['date']}\n\n";

        $subtotal = 0;
        foreach ($invoiceData['items'] as $item) {
            $itemTotal = $item['price'] * $item['qty'];
            $subtotal += $itemTotal;
            $doc .= "- {$item['name']} x{$item['qty']} = " .
                   Currency::format($itemTotal) . " บาท\n";
        }

        $vat = Currency::calcVat($subtotal, 7, true);
        $total = $subtotal + $vat;

        $doc .= "\nยอดรวม: " . Currency::format($subtotal) . " บาท\n";
        $doc .= "VAT 7%: " . Currency::format($vat) . " บาท\n";
        $doc .= "รวมทั้งสิ้น: " . Currency::format($total) . " บาท\n";
        $doc .= "(" . Currency::bahtThai($total) . ")\n";

        return $doc;
    }
}

Best Practices

1. เลือกใช้ bahtThai() หรือ bahtEng() ตามสถานการณ์

// ✅ Good - ใช้ภาษาไทยสำหรับเอกสารในประเทศ
$receipt = "จำนวนเงิน: " . Currency::bahtThai($amount);

// ✅ Good - ใช้ภาษาอังกฤษสำหรับเอกสารระหว่างประเทศ
$check = "Amount in words: " . Currency::bahtEng($amount);

2. ระบุ VAT Exclusive/Inclusive อย่างชัดเจน

// ✅ Good - ระบุชัดเจน
$vat = Currency::calcVat($price, 7, true);  // ยอดไม่รวม VAT
$vat = Currency::calcVat($price, 7, false); // ยอดรวม VAT แล้ว

// ❌ Bad - พึ่ง default อาจสับสน
$vat = Currency::calcVat($price, 7); // ไม่ชัดว่า exclusive หรือ inclusive

3. ใช้ format() สำหรับการแสดงผล

// ✅ Good - อ่านง่าย มีตัวคั่น
echo Currency::format(1234567.89); // "1,234,567.89"

// ❌ Bad - อ่านยาก
echo number_format(1234567.89); // ต้องระบุพารามิเตอร์เอง

4. จัดการทศนิยมตามประเภทข้อมูล

// ✅ Good - เงินใช้ 2 ทศนิยม
$price = Currency::format($amount, 2);

// ✅ Good - เปอร์เซ็นต์ใช้ 2-4 ทศนิยม
$percent = Currency::format($rate, 4);

// ✅ Good - ปริมาณน้ำมันใช้ 3 ทศนิยม
$fuel = Currency::format($liters, 3);

ข้อควรระวัง

[!IMPORTANT]
Precision: เมื่อ $round = false, format() จะตัดทศนิยมเกิน ไม่ใช่ปัดเศษ

[!NOTE]
VAT Calculation: calcVat() คำนวณด้วยสูตรที่แม่นย้ำ ให้ผลลัพธ์เป็น float

[!WARNING]
Large Numbers: bahtThai() รองรับถึง 1 ล้านล้าน (1,000,000,000,000)

[!TIP]
String Input: ทุกเมธอดรับ string input ได้ เหมาะสำหรับข้อมูลจากฟอร์ม

คลาสที่เกี่ยวข้อง

  • Number - การจัดรูปแบบตัวเลข
  • Text - การจัดการข้อความ
  • Date - การจัดการวันที่

สรุป

คลาส Currency มี 4 เมธอดหลัก:

  1. bahtThai() - แปลงตัวเลขเป็นคำอ่านภาษาไทย
  2. bahtEng() - แปลงตัวเลขเป็นคำอ่านภาษาอังกฤษ
  3. calcVat() - คำนวณค่า VAT (รองรับทั้ง exclusive/inclusive)
  4. format() - จัดรูปแบบตัวเลขด้วยทศนิยมและตัวคั่น

เหมาะสำหรับ:

  • ระบบใบเสร็จ/ใบกำกับภาษี
  • ระบบเงินเดือน
  • ระบบบัญชี
  • ระบบ POS
  • เอกสารทางการเงิน