JavaScript: Display positive numbers with the plus sign

泪湿孤枕 提交于 2019-11-28 11:52:34
Guffa

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; };

write a js function to do it for you?

something like

var presentInteger = function(toPresent) {
    if (toPresent > 0) return "+" + toPresent;
    else return "" + toPresent;
}

you could also use the conditional operator:

var stringed = (toPresent > 0) ? "+" + toPresent : "" + toPresent;

Thanx to the comments for pointing out that "-" + toPresent would put a double -- on the string....

function format(n) {
    return (n>0?'+':'') + n;
}

something along the lines of:

if (num > 0)
{
   numa = "+" + num;
}
else
{
   numa = num.toString();
}

and then print the string numa.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!