我有一个为数字添加逗号的函数:
function commafy( num ) {
num.toString().replace( /\B(?=(?:\d{3})+)$/g, "," );
}
不幸的是,它不太喜欢小数。鉴于以下使用示例,扩展我的功能的最佳方法是什么?
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"
想必最简单的方法是先在小数点上拆分(如果有的话)。从那里去哪里最好?