1

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.

2
  • Because "2,100,000" isn't a number.... 2100000 was a number, but your formatting of it with , 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
    – Mark Baker
    Commented Mar 26, 2014 at 21:13
  • That is because "2,100,000" is not a number. Its a string. Take out the commas for Js usage.
    – Jake N
    Commented Mar 26, 2014 at 21:13

5 Answers 5

3

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);
2

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");
1

"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
1
  • it will alert "2101" since you only removed the first comma
    – Skwal
    Commented Mar 26, 2014 at 21:17
1

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.

0

You can use a split.join combination like this:

var numStr = "2,100,000";
var num = numStr.split(',').join('');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.