I'm using number_format function of PHP to format: 2100000 --> 2,100,000. Everything is OK But when I using 2,100,000 to calcutate with javascript then I got a message: NaN.
So how can I solve this problem?
Thank you very much.
You can remove the commas from the number using a Regex
var myNumber = "2,100,000";
myNumber = parseInt(myNumber.replace(/\,/g,''), 10);
console.log(myNumber);
Show the formatted number but echo the unformatted number elsewhere and use that in js. For example:
PHP
<div id="number" data-myvalue="<?=$number?>"><?=number_format($number)?></div>
JAVASCRIPT
var myvalue = $("#number").data("myvalue");
"2,100,000" is a string. You'll need to remove "," so that it can be parsed by JavaScript and used for calculations. It's better to pass numbers around without custom formatting. However, if you receive data in such format, you can deal with them like so:
var a = "2,100,000";
a = a.replace(/,/g, ""); //Replace all occurences of "," with ""
a = parseInt(a); //If you know it's an integer
a = parseFloat(a); //If it might be a float
a += 1;
alert(a); //Displays 2100001
number_format returns 2,100,000 which is a string. If you want to make other calculations with that in js, you will have to convert it to a integer( or float depending on what you need)
var number_string = '2,100,000';
number_string = string.replace(/[^0-9]/gi, ''); // remove non-numeric charachters
var number = parseInt(number_string); // parse the string to integer
Hope this helps.
You can use a split.join combination like this:
var numStr = "2,100,000";
var num = numStr.split(',').join('');
,
has made it a formatted string.... pass the raw number back to js, do any calculations with it as a number, and only then format it purely for display using js