javascript - Format money with negative number - Stack Overflow

I have a javascript function that works well with positive number but when input the negative number it

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, and parseFloat(null) returns NaN. – RobG Commented Jun 19, 2013 at 2:40
Add a ment  | 

2 Answers 2

Reset to default 5

There 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

相关推荐

  • javascript - Format money with negative number - Stack Overflow

    I have a javascript function that works well with positive number but when input the negative number it

    1天前
    70

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信