JavaScript:显示带加号的正数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4347016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:00:51  来源:igfitidea点击:

JavaScript: Display positive numbers with the plus sign

javascriptnumbers

提问by Soso

How would I display positive number such as 3 as +3 and negative numbers such -5 as -5? So, as follows:

我如何将正数(例如 3)显示为 +3,将负数(例如 -5)显示为 -5?所以,如下:

1, 2, 3 goes into +1, +2, +3

1, 2, 3 进入 +1, +2, +3

but if those are

但如果这些是

-1, -2, -3 then goes into -1, -2, -3

-1, -2, -3 然后进入 -1, -2, -3

回答by 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:

您还没有指定如何处理零,所以我假设它会显示为+0. 如果您想将其显示为 just 0,请改用<=运算符:

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

回答by Tom Gullen

// 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.

这将为您做到。

回答by 01001111

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

回答by hvgotcodes

write a js function to do it for you?

写一个 js 函数来为你做这件事?

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....

感谢评论指出“-”+ toPresent 会在字符串上放一个双--...

回答by Samuel

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

回答by Alex Murphy

['','+'][+(num > 0)] + num

or

或者

['','+'][Number(num > 0)] + num

It is a shorter form than the ternary operator, based on casting boolean to the number 0 or 1 and using it as an index of an array with prefixes, for a number greater than 0 the prefix '+' is used

它是比三元运算符更短的形式,基于将布尔值转换为数字 0 或 1 并将其用作具有前缀的数组的索引,对于大于 0 的数字,使用前缀“+”

回答by neiker

Modern syntax solution.

现代语法解决方案。

It also includes a space between sign and number:

它还包括符号和数字之间的空格:

function getNumberWithSign(input) {
  if (input === 0) {
    return "0"
  }

  const sign = input < 0 ? '-' : '+';

  return `${sign} ${Math.abs(input)}`;
}

回答by Mark Mayo

something along the lines of:

类似的东西:

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

and then print the string numa.

然后打印字符串numa