添加逗号或空格以每三位数分组 [英] Add commas or spaces to group every three digits

查看:84
本文介绍了添加逗号或空格以每三位数分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有将逗号添加到数字的功能:

I have a function to add commas to numbers:

function commafy( num ) {
  num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," );
}

不幸的是,它不太喜欢小数.给定以下用法示例,扩展我的功能的最佳方法是什么?

Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?

commafy( "123" )                 // "123"
commafy( "1234" )                // "1234"
                                 // Don't add commas until 5 integer digits
commafy( "12345" )               // "12,345"
commafy( "1234567" )             // "1,234,567"
commafy( "12345.2" )             // "12,345.2"
commafy( "12345.6789" )          // "12,345.6789"
                                 // Again, nothing until 5
commafy( ".123456" )             // ".123 456"
                                 // Group with spaces (no leading digit)
commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8"

大概最简单的方法是先对小数点进行分割(如果有的话).哪里最好去哪里?

Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?

推荐答案

只需用'分成两部分.并分别格式化它们.

Just split into two parts with '.' and format them individually.

function commafy( num ) {
    var str = num.toString().split('.');
    if (str[0].length >= 5) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
    }
    if (str[1] && str[1].length >= 5) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }
    return str.join('.');
}

这篇关于添加逗号或空格以每三位数分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆