问题描述
通过我的 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 添加而不是字符串连接(不总是添加整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!