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
<source lang="html4strict">
<?php
$thenumber = 9.99 * 1.07; echo "$" . $thenumber . "
"; echo "$" . sprintf ("%.2f", $thenumber);
?>
</source>
Integral that the value be displayed as a dollar amount set to two decimal places:
<source lang="html4strict">
<?php
$thenumber = 9.99 * 1.07; echo "$" . $thenumber . "
"; echo "$" . sprintf ("%.2f", $thenumber);
?>
</source>
sprintf print values to a string
<source lang="html4strict">
<?php $cost = sprintf("$%01.2f", 43.2); echo $cost; ?>
</source>
sprintf()"s built-in hex-to-decimal conversion with the %x format character
<source lang="html4strict">
function build_color($red, $green, $blue) {
return sprintf("#%02x%02x%02x", $red, $green, $blue);
}
</source>
Storing a Formatted String
<source lang="html4strict">
<?php $dosh = sprintf("%.2f", 2.334454); print "$dosh dollars"; ?>
</source>
Using a sprintf()-style message catalog
<source lang="html4strict">
<?php $LANG = "es_US"; print sprintf(msg("I am X years old."),12); ?>
</source>
Using sprintf() to ensure that one digit hex numbers (like 0) get padded with a leading 0.
<source lang="html4strict">
function build_color($red, $green, $blue) {
$redhex = dechex($red); $greenhex = dechex($green); $bluehex = dechex($blue); return sprintf("#%02s%02s%02s", $redhex, $greenhex, $bluehex);
}
</source>
Using sprintf with a variable
<source lang="html4strict">
<?php $total = sprintf("Please pay $%.2f. ", 42.4242 ); echo $total; ?>
</source>
Wrap these in a couple of functions and surround the joined array elements with parentheses
<source lang="html4strict">
<?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 "
Languages: ";
print array_values_string($countries_languages);
?>
</source>