html - Javascript adding numbers as if they were a string -
this question has answer here:
i have been playing around cookies first time, , have saving part of completed. data i'm saving numbers , important part of these nubers can add, subtract , on these. when try add number 1 of saved parametres adds them if text.
example: have cookie called value
, , when want value use script found jeffery to looks this:
function readcookie(name) { return (name = new regexp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]; }
after have collected cookie want add 1 it. lets value equals nine, when should this: value + 1 = 10
. simple math. gives me 91
. why this? know because thinks numbers string of text, how can behave numbers?
solution after reading comments learned needed put value
inside parseint()
. modified funtion say:
function readcookie(name) { return parseint((name = new regexp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]); }
the +
operator in javascript can mean mathematical addition or string concatenation. 1 based on implicit type of operands. if 1 of operands string, other converted string , you'll concatenation.
the trick math on numbers first (you can surround math portion parenthesis or math in separate statement) , inject result string.
to force string containing number character number, can use parseint()
, parsefloat()
:
var result = parseint(value, 10) + 1;
note parseint()
, should supply optional second argument, specifies radix operation. if first argument happens refer string contains hex value, result based on hex, not base 10. that's why 10 used in example.
also note both parseint()
, parsefloat()
stop after finding first non-valid characters can't treated numbers. so, in string this: "scott7marcy9"
, nan.
Comments
Post a Comment