Joshua Hansen
Joshua Hansen

Reputation: 405

number_format function of php and calculate with js

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.

Upvotes: 1

Views: 2318

Answers (5)

esym
esym

Reputation: 1

You can use a split.join combination like this:

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

Upvotes: 0

spreadzz
spreadzz

Reputation: 270

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.

Upvotes: 1

Wilmer
Wilmer

Reputation: 2511

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

Upvotes: 2

Alethes
Alethes

Reputation: 922

"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

Upvotes: 1

Skwal
Skwal

Reputation: 2160

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

Upvotes: 3

Related Questions