How to Add a Plus Sign in Front of a Positive Number in PHP?

Problem:

Adding a negative sign in front of a number is easy and the sign displays in the browser directly. But, this is not the case for positive sign. You can add a plus sign in front of a number but it will not display in the browser. But, sometimes it is required to display that plus sign.

Solution:

You can prefix a positive number with a plus sign in few ways. In the following we’ll discuss few of those.

Method 1: Using sprintf() function

Using sprintf() function, you can add plus sign in front of a number. See the example below-

<?php
$number = 500;
$number = sprintf("%+d",$number);
echo $number . "<br />";

$number = 500.00;
$number = sprintf("%+.2f",$number);
echo $number;
?>

[wpdm_file id=91]

Output:
+500+500.00

How it works:

The above sprintf() function takes two parameters. First one is format specifier which sets the rules about how the number should be formatted and the second parameter is the number itself.

Line 3 Format specifier starts with a percentage sign(%), then the + is the sign specifier which forces to add the + in front of the output. Then, d is the type specifier which tells the function to treat the supplied number (500) as a decimal integer.
Line 6 Here, the dot with 2 (.2) is the precision specifier which tells to display 2 digits after the decimal point. And, f is the type specifier which tells the function to treat the supplied number (500.00) as a float.

 

Method 2: Using printf() function

Using printf() function, you can also add plus sign in front of a number. See the example below-

<?php
    $number = 500;
    printf("%+d",$number);
    echo "<br />";
    
    $number = 500.00;
    printf("%+.2f",$number). "<br />";
?>

[wpdm_file id=92]

Output:
+500
+500.00

How it works:
printf() function works similarly as sprintf() does in the above example. The only difference is that printf() function prints the formatted number directly to the screen.

Method 3: Using str_pad() function

You can also use str_pad() function to add + sign in front of a number. See the following example-

<?php
$number = 500;
$number =  str_pad($number, 4, '+', STR_PAD_LEFT);
echo $number . "<br />";
    
$number = "500.00";
echo $number =  str_pad($number, 7, '+', STR_PAD_LEFT);
?>

[wpdm_file id=93]

Output:
+500
+500.00

How it works:
The first parameter($number) in the first example is our supplied number (500). The second parameter(4) is the desired length of output. After adding + sign the number will be +500 which is has 4 in length. The third parameter specifies the string to be used as padding. Here it is plus sign(‘+’). The fourth parameter specifies in which side we want to pad. Here, we want to add the + sign in left side, so we used STR_PAD_LEFT.

The second example works similarly to the first one.