MetaStack
MetaStack

Reputation: 3696

jquery javascript set values as float before adding

My app has a textbox on a webpage whose value is looked up and then added or subtracted to another value.

It seems to subtract well, but when adding, it interprets the value in the textbox as text, and adds on the other float as a text as well:

subtracted a few times, then added as text

Here's the source code of the thing changing:

  $('#mymoney').val($('#mymoney').val() +  $prevevent.close);

//...or when subtracting:...//

  $('#mymoney').val($('#mymoney').val() -  $prevevent.close);

How to I tell the mymoney to be interpreted as a float instead of a string?

Upvotes: 3

Views: 1881

Answers (3)

yincheng
yincheng

Reputation: 21

This is simple by using parseFloat

$('#mymoney').val(parseFloat($('#mymoney').val()) + $prevevent.close);

Because JS will interpretes the other hand to string if either operator hand is a string. Or, you can use Number() to parse string to (int or float) number like:

$('#mymoney').val(Number($('#mymoney').val()) + $prevevent.close);

But the parseInt or parseFloat is prefer, because it acts more normally than Number. For Example, Number will parse null and "" to 0, and erase the 0 at the beginning of a number although it may represent an octal digit. Additionally, parseInt will return the correct part until it can't be parsed, like: parseInt("15abc") returns 15.

Upvotes: 1

AdityaParab
AdityaParab

Reputation: 7100

Other answers are correct. However, here is another syntactical spice of magic that will do wonders for integer values.

Instead of using parseInt you can just prepend your expression with a + and it will parse the following value to integer.

$('#mymoney').val( (+$('#mymoney').val()) + $prevevent.close);

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

This is because .val() is reading the value as a string and concatinating. You can parse it into a integer with parseInt():

$('#mymoney').val( parseInt($('#mymoney').val()) +  $prevevent.close);

For float values use parseFloat():

$('#mymoney').val( parseFloat($('#mymoney').val()) +  $prevevent.close);

Upvotes: 4

Related Questions