Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure javascript addition instead of string concatenation (Not always adding integers)

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?

like image 275
dnc253 Avatar asked Oct 19 '12 20:10

dnc253


2 Answers

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.

like image 59
kitti Avatar answered Sep 20 '22 15:09

kitti


It is reasonably safe to always use parseFloat even if you are given an integer. If you must use the appropriate conversion, you could match for a decimal point and use the appropriate function.

like image 22
Asad Saeeduddin Avatar answered Sep 18 '22 15:09

Asad Saeeduddin