问题描述
通过我的javascript库,我最终得到一个代表数字的字符串。现在我想在不进行字符串连接的情况下对该数字进行预处理。解决方案很简单(
,。但是我的字符串可能是浮点数或整数,并且在添加时,我不知道它将是什么。有没有办法确保添加发生,无论它是浮点数还是整数?
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而不是字符串连接(并不总是添加整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!