JavaScript:使用加号显示正数 [英] JavaScript: Display positive numbers with the plus sign

查看:1087
本文介绍了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

这篇关于JavaScript:使用加号显示正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆