2

I promise that I've done my homework on this. It's a basic question, but I'm not terribly familiar with Jquery. Assume the following...

var cac = parseInt($("#currentAccess").val());
var acn = parseInt($("#addCapital").val());
var tn = (cac + acn);

How do I then take the variable tn, do a replace on it, and output it? This is an example that doesn't work...

$("#totalNeedG").append("<p>$" + tn.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + "</p>");

Thanks for this simple help!

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636

2 Answers2

5

.replace() is a String method. Not a Number method.

Convert it to a String.

var tn = ((cac + acn) + '');
user113716
  • 318,772
  • 63
  • 451
  • 440
3

String(yourNumber) returns a string containing your number. To convert it back, use parseInt(yourString, 10).


And, as you are not doing it, ALWAYS use the second argument if parseInt(str, base)! If you don't, the base is determined automatically which is almost never what you want:

parseInt('010') == 8 // 0-prefix means octal
parseInt('0xff') == 255 // 0x-prefix means hex

While it's unlikely that somebody puts a number starting with 0x in a field chances are high someone puts a leading zero for some reason.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636