JavaScript:用加号显示正数

2022-01-17 00:00:00 numbers javascript

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

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

1、2、3进入+1、+2、+3

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

但如果是的话

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

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

推荐答案

你可以使用这样的简单表达式:

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.

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

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

相关文章