PHP/String/sprintf
Содержание
- 1 integer displayed as a dollar amount set to two decimal places
- 2 Integral that the value be displayed as a dollar amount set to two decimal places:
- 3 sprintf print values to a string
- 4 sprintf()"s built-in hex-to-decimal conversion with the %x format character
- 5 Storing a Formatted String
- 6 Using a sprintf()-style message catalog
- 7 Using sprintf() to ensure that one digit hex numbers (like 0) get padded with a leading 0.
- 8 Using sprintf with a variable
- 9 Wrap these in a couple of functions and surround the joined array elements with parentheses
integer displayed as a dollar amount set to two decimal places
<?php
$thenumber = 9.99 * 1.07;
echo "$" . $thenumber . "<br />";
echo "$" . sprintf ("%.2f", $thenumber);
?>
Integral that the value be displayed as a dollar amount set to two decimal places:
<?php
$thenumber = 9.99 * 1.07;
echo "$" . $thenumber . "<br />";
echo "$" . sprintf ("%.2f", $thenumber);
?>
sprintf print values to a string
<?php
$cost = sprintf("$%01.2f", 43.2);
echo $cost;
?>
sprintf()"s built-in hex-to-decimal conversion with the %x format character
function build_color($red, $green, $blue) {
return sprintf("#%02x%02x%02x", $red, $green, $blue);
}
Storing a Formatted String
<?php
$dosh = sprintf("%.2f", 2.334454);
print "$dosh dollars";
?>
Using a sprintf()-style message catalog
<?php
$LANG = "es_US";
print sprintf(msg("I am X years old."),12);
?>
Using sprintf() to ensure that one digit hex numbers (like 0) get padded with a leading 0.
function build_color($red, $green, $blue) {
$redhex = dechex($red);
$greenhex = dechex($green);
$bluehex = dechex($blue);
return sprintf("#%02s%02s%02s", $redhex, $greenhex, $bluehex);
}
Using sprintf with a variable
<?php
$total = sprintf("Please pay $%.2f. ", 42.4242 );
echo $total;
?>
Wrap these in a couple of functions and surround the joined array elements with parentheses
<?php
function array_values_string($arr) {
return sprintf("(%s)", implode(", ", array_values($arr)));
}
function array_keys_string($arr){
return sprintf("(%s)", implode(", ", array_key($arr)));
}
$countries_languages = array("Germany" => "German", "France" => "French", "Spain" => "Spanish");
print "Countries: ";
print array_keys_string($countries_languages);
print "<br />Languages: ";
print array_values_string($countries_languages);
?>