0

I use Number("1,255,558.3652") to convert this string to number,but the result in console tells me "Nan".

In my html code,I use:

 <input id="text_target_value" class="text-right number" type="text" onkeyup="value=value.replace(/[^\d{1,}\.\d{1,}|^\d{1,}\%|\d{1,}]/g,'')"/> 

to format the input,when I use:

var page_goal_val=Number($("#text_target_value").val());

to get the value,it said "Nan",so what should I do?

2 Answers2

2

Number doesn't recognize numeric strings with commas in them. Strip out all the commas first:

console.log(Number(
  "1,255,558.3652".replace(/,/g, '')
));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Your input element allows the values such as 123....123. And if you do:

Number(
  "123....123".replace(/,/g, '')
)

It will still give you NaN. To prevent from that and also as recommended for floating values, use parseFloat() instead of Number(). Using that, it will prevent from NaN output:

You get 1245634 (but not NaN) which should be correct

parseFloat(
  "12,456,34...123".replace(/,/g, '')
);

console.log(parseFloat(
  "12,456,34...123".replace(/,/g, '')
));

You get 1234564.123

parseFloat(
  "1,234,564.123".replace(/,/g, '')
);

console.log(parseFloat(
  "1,234,564.123".replace(/,/g, '')
));
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62