phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Formatting Numbers with Commas

Tag: number, number format, commas   Category: PHP Application, PHP Basic
post: 16 Mar 2008 read: 202


PHP Number Tips - Part 3: If you want to make a large number readable by using commas between groups of thousands, you can use PHP's number_format( ) function such as:

<?php
//define number
$amount = 3957459.7398;

//round and format number with commas
//result: "3,957,460"
$formattedAmount = number_format($amount);
echo $formattedAmount;
?>

The number_format( ) is a great tool to use in order to format large integer or floating-point numbers. Note that the output of the function is a string, not a number, and so it cannot be used for further numeric manipulation. If you have a floating-point number and don't want to round it up to an integer, you can pass number_format( ) a second argument which will control the number of decimals the formatted number should certain.


<?php
//define number
$amount = 3957459.7398;

//format number with commas and 2 decimal places
//result: "3,957,459.74"
$formattedAmount = number_format($amount, 2);
echo $formattedAmount;
?>

Furthermore, you can accomplish a custom decimal and/or thousands separator by passing number_format( ) two additional arguments. The first is for the decimal separator and the second is for the thousands separator. Here is the example beneath:


<?php
//define number
$amount = 3957459.7398;

//format number with custom separator
//result: "3'957'459,74"
$formattedAmount = number_format($amount, 2, ',', '\'');
echo $formattedAmount;
?>



| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting