我需要设计一个函数来原样返回负数,但如果它已经不存在,则应该在数字的开头添加一个 +
符号。
例子:
Input Output
----------------
+1 +1
1 +1
-1 -1
它将只获得数字输入。
function formatNum($num)
{
# something here..perhaps a regex?
}
这个函数会在echo/print
中被调用多次,所以越快越好。
最佳答案
您可以将正则表达式用作:
function formatNum($num){
return preg_replace('/^(\d+)$/',"+$1",$num);
}
但我建议 不要 使用 regex
来处理这种微不足道的事情。最好使用sprintf这里是:
function formatNum($num){
return sprintf("%+d",$num);
}
An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
关于php - 如何在PHP中用加号前缀正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2682397/