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 添加而不是字符串连接(不总是添加整数)


基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01