JavaScript: Display positive numbers with the plus sign

You can use a simple expression like this:

(n<0?"":"+") + n

The conditional expression results in a plus sign if the number is positive, and an empty string if the number is negative.

You haven't specified how to handle zero, so I assumed that it would be displayed as +0. If you want to display it as just 0, use the <= operator instead:

(n<=0?"":"+") + n

// Forces signing on a number, returned as a string
function getNumber(theNumber)
{
    if(theNumber > 0){
        return "+" + theNumber;
    }else{
        return theNumber.toString();
    }
}

This will do it for you.


printableNumber = function(n) { return (n > 0) ? "+" + n : n; };

A modern solution would be to use Intl.NumberFormat

const myNumber = 5;

new Intl.NumberFormat("en-US", {
    signDisplay: "exceptZero"
}).format(myNumber);

depending on what myNumber is it will display positive or negative sign, except when it's a 0.