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.
Update:
Thank you all for the answers. I must tell the sprintf
based solution is really fast.
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: