在 PHP 中將數字格式化為美元金額

John Wachira 2023年1月30日
  1. 在 PHP 中使用 number_format 函式將數字格式化為美元金額
  2. 在 PHP 中使用 NumberFormatter::formatCurrency 函式將數字格式化為美元金額
  3. 在 PHP 中使用正規表示式將數字格式化為美元金額
  4. 在 PHP 中手動將數字格式化為美元金額
在 PHP 中將數字格式化為美元金額

本教程文章將通過示例介紹在 PHP 中將數字格式化為美元金額的不同方法。這些包括:

  • number_format
  • NumberFormatter::formatCurrency
  • Regular expressions
  • Manual format

我們還將看看為什麼不再使用 money_format 函式。

在 PHP 中使用 number_format 函式將數字格式化為美元金額

我們使用 number_format 函式來排列一個以千為單位的值,同時新增小數位和貨幣型別。

該函式有四個引數:

number_format(NUMBER, DECIMAL DIGITS, THOUSANDS SEPARATOR, DECIMAL SEPARATOR)
  • 數字是要格式化的值。
  • 小數位數指定小數位數。
  • 小數分隔符標識用於小數點的字串。
  • 千位分隔符指示用作千位分隔符的字串。

值得注意的是,如果千位分隔符引數正在使用中,其他三個必須伴隨它才能使你的程式碼工作。

示例程式碼:

<?php

//  NUMBER
$amount = 123.45;

//  TO USD - $123.45
$usd = "$" . number_format($amount, 2, ".");
echo $usd;
?>

輸出:

$123.45

在 PHP 中使用 NumberFormatter::formatCurrency 函式將數字格式化為美元金額

這是將數字格式化為顯示不同貨幣的字串的最新且可以說是最簡單的方法。

確保在 php.ini 中啟用 extension=intl

你應該記住三個引數:

  • 格式化程式,即 NumberFormatter 物件。
  • 金額,即數字貨幣值。
  • ISO 4217 規定使用的貨幣。

示例程式碼:

<?php
// NUMBER
$amount = 123;

// TO USD - $123.00
$fmt = new NumberFormatter("en_US",  NumberFormatter::CURRENCY);
$usd = $fmt->formatCurrency($amount, "USD");
echo $usd;
?>

輸出:

$123.00

示例二:

<?php
// NUMBER
$amount = 123.456;

// TO USD - $123.46
$fmt = new NumberFormatter("en_US",  NumberFormatter::CURRENCY);
$usd = $fmt->formatCurrency($amount, "USD");
echo $usd;
?>

輸出:

$123.46

在 PHP 中使用正規表示式將數字格式化為美元金額

這種方法是一整罐蠕蟲。進入它的細節只會讓你感到困惑。

此方法將數字排列為數千,同時新增你選擇的貨幣符號。

讓我們看一個例子:

<?php
// NUMBER
$amount = 0.13;

// REGULAR EXPRESSION
$regex = "/\B(?=(\d{3})+(?!\d))/i";
$usd = "$" . preg_replace($regex, ",", $amount);
echo $usd;
?>

輸出:

$0.13

在 PHP 中手動將數字格式化為美元金額

這種方法相當於用蠻力撬鎖。此方法使你可以使用所需的任何格式。

讓我們看一個例子:

<?php
// FOR A DOLLAR CURRENCY
function curformat ($amount) {
  //  SPLIT WHOLE & DECIMALS
  $amount = explode(".", $amount);
  $whole = $amount[0];
  $decimal = isset($amount[1]) ? $amount[1] : "00" ;

  //  ADD THOUSAND SEPARATORS
  if (strlen($whole) > 3) {
    $temp = ""; $j = 0;
    for ($i=strlen($whole)-1; $i>=0; $i--) {
      $temp = $whole[$i] . $temp;
      $j++;
      if ($j%3==0 && $i!=0) { $temp = "," . $temp; }
    }
    $whole = $temp;
  }

  //  RESULT
  return "\$$whole.$decimal";
}

//  UNIT TEST
echo curformat(100); // $100.00

輸出:

$100.00

上述方法應將數字格式化為顯示美元和美分的字串。

還有另一種稱為 money_format 的方法,但它不適用於 Windows。我們強烈建議你不要使用這個函式,因為它已經被棄用。

作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn