I have a javascript function that works well with positive number but when input the negative number it alert NaN
:
function formatMoney(number) {
number = parseFloat(number.toString().match(/^\d+\.?\d{0,2}/));
//Seperates the ponents of the number
var ponents = (Math.floor(number * 100) / 100).toString().split(".");
//Comma-fies the first part
ponents [0] = ponents [0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return ponents.join(".");
}
alert(formatMoney(-11));
Here is the example in jsFiddle /
thanks for any help
I have a javascript function that works well with positive number but when input the negative number it alert NaN
:
function formatMoney(number) {
number = parseFloat(number.toString().match(/^\d+\.?\d{0,2}/));
//Seperates the ponents of the number
var ponents = (Math.floor(number * 100) / 100).toString().split(".");
//Comma-fies the first part
ponents [0] = ponents [0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return ponents.join(".");
}
alert(formatMoney(-11));
Here is the example in jsFiddle http://jsfiddle/longvu/wRYsU/
thanks for any help
Share edited Jun 19, 2013 at 2:19 John Koerner 38.1k8 gold badges92 silver badges140 bronze badges asked Jun 19, 2013 at 2:18 Long VuLong Vu 2051 gold badge3 silver badges10 bronze badges 2-
What do you think
.match(/^\d+\.?\d{0,2}/))
does? – zerkms Commented Jun 19, 2013 at 2:19 -
If match does not find a match, it returns
null
, andparseFloat(null)
returnsNaN
. – RobG Commented Jun 19, 2013 at 2:40
2 Answers
Reset to default 5There is no allowance for a leading sign in /^\d+\.?\d{0,2}/
, it must start with a digit.
First step is to allow for that, with something like:
/^-?\d+\.?\d{0,2}/
If you place that in your example jsfiddle script, you get a dialog box with -11
rather than NaN
.
Seems to me you can get rid of the first regular expression (unless you want to validate input) and use:
function formatAsMoney(n) {
n = (Number(n).toFixed(2) + '').split('.');
return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + (n[1] || '00');
}
There were once issues with toFixed, but I don't think it's a problem any more.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744919919a4601069.html
评论列表(0条)