JIYIK CN >

Current Location:Home > Learning > PROGRAM > PHP >

Formatting a number as a dollar amount in PHP

Author:JIYIK Last Updated:2025/04/13 Views:

This article will cover different ways to format numbers as dollar amounts in PHP with examples. These include:

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

We'll also look at why money_formatthe function is no longer used.


Use the function in PHP number_formatto format a number as a dollar amount

We use number_formatthe function to round a value in thousands while adding decimal places and currency type.

This function has four parameters:

number_format(NUMBER, DECIMAL DIGITS, THOUSANDS SEPARATOR, DECIMAL SEPARATOR)
  • number is the value to be formatted.
  • Decimal places specifies the number of decimal places.
  • Decimal separator identifies the string used for the decimal point.
  • Thousands separator indicates the string used as the thousands separator.

It's worth noting that if the thousands separator parameter is in use, the other three must accompany it in order for your code to work.

Sample code:

<?php

//  NUMBER
$amount = 123.45;

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

Output:

$123.45

Use the function in PHP NumberFormatter::formatCurrencyto format a number as a dollar amount

This is the newest and arguably simplest way to format numbers into strings displaying different currencies.

Make sure php.iniit is enabled in extension=intl.

There are three parameters you should remember:

  • A formatter, a NumberFormatterobject.
  • Amount, i.e. digital currency value.
  • The currency used is specified by ISO 4217.

Sample code:

<?php
// NUMBER
$amount = 123;

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

Output:

$123.00

Example 2:

<?php
// NUMBER
$amount = 123.456;

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

Output:

$123.46

正则表达式Formatting numbers as dollar amounts in PHP

This approach is a whole can of worms. Going into the details of it will only confuse you.

This method rounds the number up to thousands while adding the currency symbol of your choice.

Let’s look at an example:

<?php
// NUMBER
$amount = 0.13;

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

Output:

$0.13

Manually formatting a number as a dollar amount in PHP

This method is equivalent to picking the lock by brute force. This method allows you to use any format you want.

Let’s look at an example:

<?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

Output:

$100.00

The above method should format the number into a string showing dollars and cents.

There is another money_formatmethod called , but it does not work on Windows. We strongly recommend that you do not use this function as it is deprecated.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial