admin管理员组文章数量:1430517
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.
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.
Share Improve this question asked Mar 26, 2014 at 21:12 Joshua HansenJoshua Hansen 4051 gold badge8 silver badges21 bronze badges 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 mas for Js usage. – Jake N Commented Mar 26, 2014 at 21:13
5 Answers
Reset to default 3You can remove the mas 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 bination like this:
var numStr = "2,100,000";
var num = numStr.split(',').join('');
本文标签: javascriptnumberformat function of php and calculate with jsStack Overflow
版权声明:本文标题:javascript - number_format function of php and calculate with js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745556768a2663234.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论