JavaScript: Display positive numbers with the plus sign(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:用加号显示正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript:用加号显示正数


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01