0%

JAVA实现数字千位分隔符

DecimalFormat

1
new DecimalFormat(",###").format(new BigDecimal(1234567890).longValue())

String.format

1
String.format("%,d",new BigDecimal(1234567890).longValue())

正则表达式

1
String.valueOf(new BigDecimal(1234567890).longValue()).replaceAll("(\\d)(?=(\\d{3})+\$)", "\$1,")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/perl

use strict;
use warnings;
my $num = 1234556789;
#纯数据模式
$num =~ s/(?<=\d)(?=(\d{3})+$)/,/g;
print $num,"\n";
#带有小数点模式
$num = 123456.1234;
$num =~ s/(?<!\.\d)(?<=\d)(?=(\d{3})+\b)/,/g;
print $num,"\n";
#大于5位之后。。。
#\K 模式,可变长否定向后环视;\K容许在它之前的模式只匹配而不被替换。替换操作只对\K之后的字符串部分有效。
$num = 123456.12345;
$num =~ s/(?<!\.)(?:\b|\G)\d+?\K(?=(\d{3})+\b)/,/g;
print $num,"\n";
1
2
3
4
OUTPUT:
1,234,556,789
123,456.1234
123,456.12345