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 i开发者_StackOverflow社区nput.
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.
You can use regex as:
function formatNum($num){
return preg_replace('/^(\d+)$/',"+$1",$num);
}
But I would suggest not using regex
for such a trivial thing. Its better to make use of sprintf here as:
function formatNum($num){
return sprintf("%+d",$num);
}
From PHP Manual for sprintf:
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.
function formatNum($num) {
return ((float) $num>0)?'+'.$num:$num;
}
function formatNum($num) {
$num = (int) $num; // or (float) if you'd rather
return (($num >= 0) ? '+' : '') . $num; // implicit cast back to string
}
The simple solution is to make use of format specifier in printf() function.
For example,
$num1=2;
$num2=-2;
printf("%+d",$num1);
echo '<br>';
printf("%+d",$num2);
gives the output
+2
-2
In your case
function formatNum($num){
return printf("%+d",$num);
}
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.
// Non float safe version
function formatNum($num) {
return (abs($num) == $num ? '+' : '') . intval($num);
}
// Float safe version
function formatNum($num) {
return
(abs($num) == $num ? '+' : '')
. (intval($num) == $num ? intval($num) : floatval($num));
}
// Float safe version, alternative
function formatNum($num) {
return
(abs($num) == $num ? '+' : '')
// Add '1' to $num to implicitly cast it to a number
. (is_float($num + 1) ? floatval($num) : intval($num));
}
Try this:
$fmt = new NumberFormatter('es_ES', NumberFormatter::DECIMAL);
$fmt->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$result = $fmt->format(10000);
Result will be: +10.000
Exactly works NumberFormatter::POSITIVE_SUFFIX
, you will receive 10.000+
精彩评论