Dec
04
2008

Strings and Patterns: Formatting

Formatting

Their are different methods of formatting strings in PHP some are to handle data types (e.g. Currency) and others are more complex. With currency many countries format it differently, where they put the commas for example if your website is hosted in Europe its likely that that the sysadmn has set local information to Europe. Therefore if US number formatting is required use:

setlocale (LC_MONETARY, ’en_US’);

Their are many more setlocale settings you can change such as Money, Numbers, Time and Error Messages (php.net setlocale). To save us looking up every setting we can use a generic umbrella setlocal setting, In this example we set them all in United Kingdom (Great Britain) format:

setlocale (LC_ALL, 'en_gb');

setlocale affects the entire process inside which it is executed, rather than the
individual script

Formatting: Numbers

We use number formatting to output numbers with formatting to separate its digits into thousands and decimal points. This is done with the number_format(); its not effected by locale (mentioned above), the function can have 1,2 or 4 arguments.
If only one argument is given, the default formatting is used: the number will be rounded to the nearest integer, and a comma will be used to separate thousands.
If two arguments are given, the number will be rounded to the given number of decimal places and a period and comma will be used to separate decimals and thousands.
If four arguments are given, the number of decimal places given, and number_format() will use the first character of the third and fourth arguments as decimal and thousand.

$number = 1000000.119; //The number
$numberofdecimals = 2; //What do you want Quantity of digits after decimal points
$decimalpointseperator = "."; //What do you want to separate the decimal point by?
$thousandseperator = ","; //What do you want to separate the thousands by?
echo number_format($number, $numberofdecimals, $decimalpointseperator, $thousandseperator); //shows 100,0000.11
//-------------------------------------------
echo number_format("100000.698"); // Shows 100,001
echo number_format("100000.698", 3, ",", " "); // Shows 100 000,698

Formatting: Currency

As we mentioned before Currency is When using money_format(), we must specify the formatting rules we want to use by passing the function a specially-crafted string that consists of a percent symbol (%) followed by a set of flags that determine the minimum width of the resulting output, its integer and decimal precision and a conversion character that determines whether the currency value is formatted using the locale’s national or international rules.

setlocale(LC_MONETARY, "en_US");
echo money_format(%.2n’, "100000.698"); // Outputs $100,000.70
//-----
echo money_format(%.2i’, "100000.698"); // Outputs USD 100,000.70
//-------------------
setlocale(LC_MONETARY, "ja_JP.UTF-8");
echo money_format(%.2n’, "100000.698"); // Outputs ¥100,000.70
//-----
echo money_format(%.2i’, "100000.698"); // Output JPY 100,000.70

As you can see formatting is useful, you will notice that both currency rounded the number. Remember that setlocale has many different changes not just the prefix symbol, it also changes rounding. In this example if we don’t specify how many decimals we want:

setlocale(LC_MONETARY, "en_US");
echo money_format(%i’, "100000.698"); //Output USD 100,000.70 (as expected)
setlocale(LC_MONETARY, "ja_JP");
echo money_format(%i’, "100000.698"); //Output JPY 100,001 (japanise round up, they dont use cents)
 
<h1>Formating: General</h1>
As numeracy uses money_format(); and number_format(); regular strings can use <strong>printf();</strong> and related functions (sprintf(); fprintf();)
printf(); function prints data to the scripts output
sprntf(); function returns data to a variable
fprintf(); function saves data to a file
 
The formatting string usually contains a combination of literal text—that is copied directly into the function’s output—and specifiers that determine how the input should be formatted. The specifiers are then used to format each input parameter in the order in which they are passed to the function (thus, the first specifier is used to format the first data parameter, the second specified is used to format the second parameter, and so on).
 
Generally formating always starts with a percent symbol, you can still format showing percent by escaping it (%%). After the percentage symbol t is followed by a specification token which identifies type:
<strong>Sign Specifier (+ or -)</strong> determine how signed numbers are to be rendered
<strong>Padding specifier</strong> that indicates what character should be used to make up the required output length, should the input not be long enough on its own
<strong>alignment specifier</strong> An alignment specifier that indicates if the output should be left or right aligned
<strong>numeric width specifier</strong> A numeric width specifier that indicates theminimumlength of the output
<strong>precision specifier</strong> A precision specifier that indicates how many decimal digits should be displayed
for floating-point numbers
 
Common Type Specifiers:
b Output an integer as a Binary number.
c Output the character which has the input integer as its ASCII value.
d Output a signed decimal number
e Output a number using scientific notation (e.g., 3.8e+9)
u Output an unsigned decimal number
f Output a locale aware float number
F Output a non-locale aware float number
o Output a number using its Octal representation
s Output a string
x Output a number as hexadecimal with lowercase letters
X Output a number as hexadecimal with uppercase letters
 
<pre lang="php">$n = 123;
$f = 123.45;
$s = "A string";
 
printf ("%d", $n); // prints 123
printf ("%d", $f); // prints 1
 
// Prints "The string is A string"
printf ("The string is %s", $s);
 
// Example with precision
printf ("%3.3f", $f); // prints 123.450
 
// Complex formatting
function showError($msg, $line, $file){
	return sprintf("An error occured in %s on "."line %d: %s", $file, $line, $msg);
}
showError ("Invalid deconfibulator", __LINE__, __FILE__);

Parsing Formatted Input

The function sscanf(); is not used for formatting data, it instead is is used to parse formatted input.

The sscanf() family of functions works in a similar way to printf(), except that, instead

$data =123 456 789’;
$format =%d %d %d’;
var_dump (sscanf ($data, $format));

When this code is executed, the function interprets its input according to the rules specified in the format string and returns an array that contains the parsed data:

array(3) {
[0]=>
int(123)
[1]=>
int(456)
[2]=>
int(789)
}

Note that the data must match the format passed to sscanf() exactly—or the function will fail to retrieve all the values. For this reason, sscanf() is normally only useful in those situations in which input follows a well-defined format (that is, it is not provided by the user!).

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Live
  • StumbleUpon
  • Technorati
  • TwitThis
Written by Adam in: 07. Strings and Patterns |

No Comments »

RSS feed for comments on this post. TrackBack URL

Leave a comment

WordPress Powered, Theme by TheBuckmaker.com | Add to Technorati Favorites. | RSS and Comments RSS