- 论坛徽章:
- 0
|
本帖最后由 yeahnoob 于 2014-09-02 23:01 编辑
实际应用环境中,可能是直接用cpan现成的模块,比如- use CLDR::Number::Format::Decimal;
复制代码 ,生产效率会比自己动手高很多。
比如下面这样子:
- Perl> use Number::Format;
- Perl> my $a= new Number::Format;
- Number::Format=HASH(0xe1c558)
- Perl> my $b=$a->format_number("-99123123123.4564560",2);
- -99,123,123,123.46
复制代码 但是如果想作为单独的一个例子——比较费神——使劲Google了一会儿,结果如下:
perldoc perllocale里的一个例子- use POSIX qw(locale_h);
- # Get some of locale's numeric formatting parameters
- my ($thousands_sep, $grouping) =
- @{localeconv()}{'thousands_sep', 'grouping'};
- # Apply defaults if values are missing
- $thousands_sep = ',' unless $thousands_sep;
- # grouping and mon_grouping are packed lists
- # of small integers (characters) telling the
- # grouping (thousand_seps and mon_thousand_seps
- # being the group dividers) of numbers and
- # monetary quantities. The integers' meanings:
- # 255 means no more grouping, 0 means repeat
- # the previous grouping, 1-254 means use that
- # as the current grouping. Grouping goes from
- # right to left (low to high digits). In the
- # below we cheat slightly by never using anything
- # else than the first grouping (whatever that is).
- if ($grouping) {
- @grouping = unpack("C*", $grouping);
- } else {
- @grouping = (3);
- }
- # Format command line params for current locale
- for (@ARGV) {
- $_ = int; # Chop non-integer part
- 1 while
- s/(\d)(\d{$grouping[0]}($|$thousands_sep))/$1$thousands_sep$2/;
- print "$_";
- }
- print "\n";
复制代码 有人写的另外一个例子,这个例子的匹配表达也很容易被读懂。- # from Andrew Johnson <[email]ajohnson@gpu.srv.ualberta.ca[/email]>
- sub commify {
- my $input = shift;
- $input = reverse $input;
- $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
- return reverse $input;
- }
复制代码 上面这个sub 可以解决带小数点的数字添加千位分隔符问题
——例如对于具体的数字$a=123123123.456456,按如下步骤转换:
- yeahnoob@yeahnoob-desktop:~$ perlconsole
- Perl Console 0.4
- Perl> my $a=123123123.456456;
- 123123123.456456
- Perl> $a=reverse $a;
- 654654.321321321
- Perl> $a =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
- 2
- Perl> $a=reverse $a;
- 123,123,123.456456
- Perl> $a
- 123,123,123.456456
- Perl>
复制代码 |
|