How to ensure javascript addition instead of string concatenation (Not always adding integers)(如何确保 javascript 添加而不是字符串连接(不总是添加整数))
问题描述
通过我的 javascript 库,我得到了一个代表数字的字符串.现在我想对该数字进行加法运算,而不是进行字符串连接.解决方法很简单(怎么做我使用 javascript (jquery) 将整数值添加到返回字符串的值中?、).但是我的字符串可以是浮点数或整数,并且在添加时,我不知道它会是哪个.有没有办法确保无论是浮点数还是整数都发生加法?
Through my javascript library, I end up with a string that represents a number. Now I want to preform an addition on that number without it doing a string concatenation instead. The solution is easy ( How do I add an integer value with javascript (jquery) to a value that's returning a string?, How to make an addition instead of a concatenation) if your number is always in integer. However my string could be a float or an integer, and at the time of the addition, and I don't know which it will be. Is there a way to make sure the addition happens regardless of whether it's a float or integer?
推荐答案
尝试使用 parseFloat
.输入变量将被转换为浮点数,无论字符串包含整数还是浮点数都有效.您的结果将始终为浮点数.
Try using parseFloat
. The input variables will be converted to floats, which will work whether the string contains an integer or a float. Your result will always be a float.
这篇关于如何确保 javascript 添加而不是字符串连接(不总是添加整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何确保 javascript 添加而不是字符串连接(不总是添加整数)


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