PHP Formatting Currency in Your App: Making Money Readable

Spread the love

PHP Formatting Currency in Your App: When it comes to formatting currency with commas, it’s important to make sure that the representation is accurate. We often face difficulties when it comes to storing and managing financial data within applications. Typical inquiries like “How to format money using comma?“, “Should I use float data type in my SQL DB?“, and “Why operations with money is so complex?“. I will try to take a practical approach for managing money in your applications, drawing insights from real-world scenarios.

Some Examples

$amount = 1000;
$formatted_amount_1 = number_format($amount, 2); // 1,000.00
$formatted_amount_2 = number_format($amount, 0); // 1,000
$formatted_amount_3 = number_format($amount);    // 1,000

// Using different separators
$formatted_amount_4 = number_format($amount, 2, ',', "'"); // 1'000,00
$formatted_amount_5 = number_format($amount, 2, '.', '-'); // 1.000-00

// With a different number of decimal places
$formatted_amount_6 = number_format($amount, 3); // 1,000.000

// With currency symbol
$formatted_amount_7 = '$' . number_format($amount, 2); // $1,000.00
$formatted_amount_8 = number_format($amount, 2) . ' USD'; // 1,000.00 USD

// With thousands separator but without decimal places
$formatted_amount_9 = number_format($amount, 0, '.', ','); // 1,000

// With space as a thousands separator
$formatted_amount_10 = number_format($amount, 2, '.', ' '); // 1 000.00

// With a custom thousands separator and decimal point
$formatted_amount_11 = number_format($amount, 2, '*', '^'); // 1^000*00

// Using locale settings
setlocale(LC_MONETARY, 'en_US.UTF-8');
$formatted_amount_12 = money_format('%i', $amount); // $1,000.00

Why not store money as a decimal?

A crucial point to remember: never store money in the database using a float data type. It can lead to unforeseen complexities down the line. Instead, we recommend storing monetary values as integers.

But why integers? It’s actually quite simple. We achieve this by multiplying the actual value by 100 before storing it. Here’s how it translates:

  • Instead of storing 50.56, store 5056.
  • Instead of storing 455.15, store 45515.
  • Instead of storing 8997.23, store 899723.

If you are Interested in Laravel then please read New Laravel 11 has been officially released: Welcome Reverb

Benefits of Storing Money as Integers

This approach offers several advantages:

  • Precision: By storing the value as a integers, we eliminate the potential rounding errors associated with floats.
  • Simplicity: Calculations become easier to handle because you’re working with integers instead of decimals.
  • Data Integrity: Storing money as a string ensures the data remains consistent and unaltered, preventing unexpected decimal point shifts.

PHP Formatting Currency in Your App

We divide the string by 100 and add a comma for readability when displaying the recorded monetary value. This method ensures precise calculations and easy financial data presentation. We will discuss more on this.

Real Life Example

Let’s consider a practical example – a “Daily Expense” application. We’ll focus on storing daily expense records and displaying the corresponding monetary values within the app.

Let’s Prepare the Database:

Here’s an example of how to create the expenses table in your MySQL database:

CREATE TABLE expenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    text VARCHAR(255),
    money VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Create Expense:

When creating expenses, we’ll store them in the database as follows, keeping in mind that we multiply the money by 100 before storing and later we will do PHP Formatting Currency in Your App:

<?php
// ... DATABASE CONNECTION

$text = "Food";
$money = "45.75";
$moneyToStore = $money * 100; // HERE WE CONVERT THE MONEY TO INTEGER

$sql = "INSERT INTO expenses (text, money) VALUES (:text, :money)";
$stmt = $pdo->prepare($sql);

$stmt->bindParam(':text', $text);
$stmt->bindParam(':money', $moneyToStore);

$stmt->execute();

Comma-Separated Money: Retrieve Data for a Day

Lets suppose following are the data in my table now:

idtextmoneycreated_atupdated_at
1Food457522-03-202422-03-2024
2Trave524522-03-202422-03-2024

Now that you understand how to store and filter expenses by date in your database, let’s explore how to do PHP Formatting Currency in Your App using number_format. Here’s an example that demonstrates fetching and displaying expenses for a specific day (PLEASE NOTICE THE COMMENTS IN THE CODE):

<?php
// ... DATABASE CONNECTION CODE

// Set date in YYYY-MM-DD format
$currentDate = "2024-03-22";

$sql = "SELECT * FROM expenses WHERE DATE(created_at) = :date";

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':date', $currentDate);
$stmt->execute();

$totalExpense = 0;

/**
 * CALCULATE TOTAL EXPENSE
 * $totalExpense : 4575 + 5245 = 9820
 */
foreach ($expenses as $expense) {
  $totalExpense += $expense['money'];
}

/**
 * HERE WE ARE CONVERTING MISC EXPENSES TO INTEGER.
 * $miscExpense : 1000.45 * 100 = 100045
 */
$miscExpense = 1000.45 * 100;

/**
 * WE CAN DO OPERATIONS HERE LIKE NORMAL INTEGERS
 * HERE ADDING MISC EXPENSES TO THE TOTAL EXPENSES OF THE DAY
 * $totalAmountWithMisc : 9820 + 100045 = 109865
 */
$totalAmountWithMisc = $totalExpense + $miscExpense;

/**
 * BEFORE DISPLAYING WE CONVERT IT BACK TO MONEY
 * HERE BEFORE DISPLAYING CONVERTING INTEGER TO MONEY
 * $totalAmountFormattedFromInteger = 1098.65
 */
$totalAmountFormattedFromInteger = $totalAmountWithMisc / 100;

/**
 * HERE FORMAT IT TO PROPER COMMA SEPARATED MONEY
 * $totalAmountCommaSeparated = 1,098.65
 */
$totalAmountCommaSeparated = number_format($totalAmountFormattedFromInteger, 2, '.', ',');

echo "<br>Total: $" . $totalAmountCommaSeparated; // $1,052.90

// ... REST OF THE CODE

The article (PHP Formatting Currency in Your App) stresses the significance of appropriately handling and formatting currency in PHP applications. We also discussed the limitations of utilizing float data types for database monetary values. I promote integer money storage for precision, simplicity, and data integrity. We also covered PHP currency formatting with commas for readability.

If you found this article helpful, consider sharing it with your network of developers or anyone who might benefit from PHP Formatting Currency in Your App.