sprintf函数用法
时间: 2023-11-25 17:52:26 浏览: 92
sprintf()函数是一个C语言标准库函数,用于将格式化的字符串写入另一个字符串中。在PHP中,sprintf()函数也被广泛使用。以下是sprintf()函数的一些用法:
1. 将整数转换为字符串并输出:
```php
$num = 123;
$str = sprintf("%d", $num);
echo $str; // 输出:123
```
2. 将浮点数转换为字符串并输出:
```php
$num = 3.1415926;
$str = sprintf("%.2f", $num);
echo $str; // 输出:3.14
```
3. 将科学计数法表示的浮点数转换为字符串并输出:
```php
$num = 1.23e6;
$str = sprintf("%.2e", $num);
echo $str; // 输出:1.23e+06
```
4. 将字符串格式化输出:
```php
$name = "Tom";
$age = 18;
$str = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $str; // 输出:My name is Tom and I am 18 years old.
```
5. 将十六进制数转换为字符串并输出:
```php
$num = 255;
$str = sprintf("%x", $num);
echo $str; // 输出:ff
```
6. 将八进制数转换为字符串并输出:
```php
$num = 255;
$str = sprintf("%o", $num);
echo $str; // 输出:377
```
7. 将二进制数转换为字符串并输出:
```php
$num = 255;
$str = sprintf("%b", $num);
echo $str; // 输出:11111111
```
8. 将字符转换为字符串并输出:
```php
$char = 'A';
$str = sprintf("%c", $char);
echo $str; // 输出:A
```
9. 将指针地址转换为字符串并输出:
```php
$var = "Hello";
$str = sprintf("%p", $var);
echo $str; // 输出:0x7f8f3c000b20
```
阅读全文