PHP/String/sprintf — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 07:07, 26 мая 2010

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