Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
846 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...