如何在 PHP 中为正数添加加号前缀
我需要设计一个函数以不变地返回负数,但如果数字已经不存在,则应在数字的开头添加一个 + 符号。
示例:
Input Output
----------------
+1 +1
1 +1
-1 -1
它将仅获得数字输入。
function formatNum($num)
{
# something here..perhaps a regex?
}
该函数将在 echo/print
中调用多次,因此越快越好。
I need to design a function to return negative numbers unchanged but should add a +
sign at the start of the number if its already no present.
Example:
Input Output
----------------
+1 +1
1 +1
-1 -1
It will get only numeric input.
function formatNum($num)
{
# something here..perhaps a regex?
}
This function is going to be called several times in echo/print
so the quicker the better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以将正则表达式用作:
但我建议不要使用
正则表达式
来处理如此琐碎的事情。最好在这里使用 sprintf :来自 sprintf 的 PHP 手册:
You can use regex as:
But I would suggest not using
regex
for such a trivial thing. Its better to make use of sprintf here as:From PHP Manual for sprintf:
简单的解决方案是在 printf() 函数中使用格式说明符。
例如,
给出输出
在您的情况下
The simple solution is to make use of format specifier in printf() function.
For example,
gives the output
In your case
试试这个:
结果将是:
+10.000
完全有效
NumberFormatter::POSITIVE_SUFFIX
,您将收到10.000+
Try this:
Result will be:
+10.000
Exactly works
NumberFormatter::POSITIVE_SUFFIX
, you will receive10.000+
好吧,这是相当旧的,可能没用,但我认为仍然有一些空间可以稍微补充。如果您已“准备好”数字:
或者,如果您确定它是一个数字:
这对负数没有任何作用,如果是正数,则仅更改为字符串。
如果不是,则添加 0 会转换为 Number,并且不会更改数字类型,例如转换为 (float) 或 (int)。如果你确定它是一个数字,则没有用,请使用第二个版本。
这可能是最快的方法
缺点是,您将得到一半结果为字符串,一半结果为数字(sprintf 将使它们全部为字符串)
Ok, this is rather old and probably useless, but I think there is still some space for a slight addition. If you have the number "ready":
Or, if you are sure it's a number:
This does nothing on negative numbers and just changes to string if positive.
Adding 0 converts to Number if it is not, and does not change the numeric type, like casting to (float) or (int). It is useless if you are sure it's a number, use the second version.
This is probably the quickest way
As a downside, you will have half results as strings and half as numbers (sprintf will make them all strings)
@unicornaddict 提供的 sprintf 解决方案非常好,而且可能是最优雅的方法。只是想无论如何我都会提供一个替代方案。不确定他们的速度如何。
The
sprintf
solution provided by @unicornaddict is very nice and probably the most elegant way to go. Just thought I'd provide an alternative anyway. Not sure how they measure up in speed.