将数字字符串转换为 PHP 中的数字 [英] String numbers into number numbers in PHP

查看:60
本文介绍了将数字字符串转换为 PHP 中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我将 00 设置为这样的值:

How come when I set 00 as a value like this:

$var = 00;

当我使用它时输出为 0?如何设置 00 使 $var++ 变为 01?

it ouputs as 0 when I use it? How can I set 00 so that $var++ would become 01?

推荐答案

PHP(以及几乎所有语言)中的数字在内部存储时不带有前导(或在十进制值的情况下,尾随)零.

Numbers in PHP (and virtually all languages) are not stored internally with leading (or in the case of decimal values, trailing) zeros.

在 PHP 中有很多方法可以显示带前导零的数字变量.最简单的方法是将您的值转换为字符串,并用零填充字符串直到它的长度正确.PHP 有一个名为 str_pad 的函数来做这给你:

There are many ways to display your numeric variables with leading zeros In PHP. The simplest way is to convert your value to a string, and pad the string with zero's until it's the correct length. PHP has a function called str_pad to do this for you:

$var = 0;
$var += 1;

// outputs '01'
echo str_pad($var, 2, '0', STR_PAD_LEFT);

或者,sprintf 系列of 函数具有用于打印零填充值的说明符:

Alternatively, the sprintf family of functions have a specifier for printing zero-padded values:

$var = 1;

// outputs '01'
printf("%02d", $var);

这篇关于将数字字符串转换为 PHP 中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆