-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathFormat.pm
executable file
·1489 lines (1211 loc) · 50.9 KB
/
Format.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Number::Format;
# Minimum version is 5.10.0. May work on earlier versions, but not
# supported on any version older than 5.10. Hack this line at your own risk:
require 5.010;
use strict;
use warnings;
=head1 NAME
Number::Format - Perl extension for formatting numbers
=head1 SYNOPSIS
use Number::Format;
my $x = new Number::Format %args;
$formatted = $x->round($number, $precision);
$formatted = $x->format_number($number, $precision, $trailing_zeroes);
$formatted = $x->format_negative($number, $picture);
$formatted = $x->format_picture($number, $picture);
$formatted = $x->format_price($number, $precision, $symbol);
$formatted = $x->format_bytes($number, $precision);
$number = $x->unformat_number($formatted);
use Number::Format qw(:subs);
$formatted = round($number, $precision, $roundoption);
$formatted = format_number($number, $precision, $trailing_zeroes);
$formatted = format_negative($number, $picture);
$formatted = format_picture($number, $picture);
$formatted = format_price($number, $precision, $symbol);
$formatted = format_bytes($number, $precision);
$number = unformat_number($formatted);
=head1 REQUIRES
Perl, version 5.8 or higher.
POSIX.pm to determine locale settings.
Carp.pm is used for some error reporting.
=head1 DESCRIPTION
These functions provide an easy means of formatting numbers in a
manner suitable for displaying to the user.
There are two ways to use this package. One is to declare an object
of type Number::Format, which you can think of as a formatting engine.
The various functions defined here are provided as object methods.
The constructor C<new()> can be used to set the parameters of the
formatting engine. Valid parameters are:
THOUSANDS_SEP - character inserted between groups of 3 digits
DECIMAL_POINT - character separating integer and fractional parts
MON_THOUSANDS_SEP - like THOUSANDS_SEP, but used for format_price
MON_DECIMAL_POINT - like DECIMAL_POINT, but used for format_price
INT_CURR_SYMBOL - character(s) denoting currency (see format_price())
DECIMAL_DIGITS - number of digits to the right of dec point (def 2)
DECIMAL_FILL - boolean; whether to add zeroes to fill out decimal
NEG_FORMAT - format to display negative numbers (def ``-x'')
ROUND_OPTION - decide to floor or normal rounding or ceil
KILO_SUFFIX - suffix to add when format_bytes formats kilobytes (trad)
MEGA_SUFFIX - " " " " " " megabytes (trad)
GIGA_SUFFIX - " " " " " " gigabytes (trad)
KIBI_SUFFIX - suffix to add when format_bytes formats kibibytes (iec)
MEBI_SUFFIX - " " " " " " mebibytes (iec)
GIBI_SUFFIX - " " " " " " gibibytes (iec)
They may be specified in upper or lower case, with or without a
leading hyphen ( - ).
If C<THOUSANDS_SEP> is set to the empty string, format_number will not
insert any separators.
The defaults for C<THOUSANDS_SEP>, C<DECIMAL_POINT>,
C<MON_THOUSANDS_SEP>, C<MON_DECIMAL_POINT>, and C<INT_CURR_SYMBOL>
come from the POSIX locale information (see L<perllocale>). If your
POSIX locale does not provide C<MON_THOUSANDS_SEP> and/or
C<MON_DECIMAL_POINT> fields, then the C<THOUSANDS_SEP> and/or
C<DECIMAL_POINT> values are used for those parameters. Formerly,
POSIX was optional but this caused problems in some cases, so it is
now required. If this causes you hardship, please contact the author
of this package at <[email protected]> (remove "SPAM" to get correct
email address) for help.
If any of the above parameters are not specified when you invoke
C<new()>, then the values are taken from package global variables of
the same name (e.g. C<$DECIMAL_POINT> is the default for the
C<DECIMAL_POINT> parameter). If you use the C<:vars> keyword on your
C<use Number::Format> line (see non-object-oriented example below) you
will import those variables into your namesapce and can assign values
as if they were your own local variables. The default values for all
the parameters are:
THOUSANDS_SEP = ','
DECIMAL_POINT = '.'
MON_THOUSANDS_SEP = ','
MON_DECIMAL_POINT = '.'
INT_CURR_SYMBOL = 'USD'
DECIMAL_DIGITS = 2
DECIMAL_FILL = 0
NEG_FORMAT = '-x'
ROUND_OPTION = 0
KILO_SUFFIX = 'K'
MEGA_SUFFIX = 'M'
GIGA_SUFFIX = 'G'
KIBI_SUFFIX = 'KiB'
MEBI_SUFFIX = 'MiB'
GIBI_SUFFIX = 'GiB'
Note however that when you first call one of the functions in this
module I<without> using the object-oriented interface, further setting
of those global variables will have no effect on non-OO calls. It is
recommended that you use the object-oriented interface instead for
fewer headaches and a cleaner design.
The C<DECIMAL_FILL> and C<DECIMAL_DIGITS> values are not set by the
Locale system, but are definable by the user. They affect the output
of C<format_number()>. Setting C<DECIMAL_DIGITS> is like giving that
value as the C<$precision> argument to that function. Setting
C<DECIMAL_FILL> to a true value causes C<format_number()> to append
zeroes to the right of the decimal digits until the length is the
specified number of digits.
C<NEG_FORMAT> is only used by C<format_negative()> and is a string
containing the letter 'x', where that letter will be replaced by a
positive representation of the number being passed to that function.
C<format_number()> and C<format_price()> utilize this feature by
calling C<format_negative()> if the number was less than 0.
C<ROUND_OPTION> is only used by C<round()> or C<format_number()>.
-1 or ROUND_FLOOR means floor, -2 or ROUND_ABS_FLOOR means absolute
floor, 1 or ROUND_CEIL means ceil, 2 or ROUND_ABS_CEIL means absolute
ceil and a 0 or ROUND_NORMAL means normal rounding. Also see the
corresponding methods C<floor()>, C<abs_floor()>, C<ceil()> and
C<abs_ceil()> for more information.
C<KILO_SUFFIX>, C<MEGA_SUFFIX>, and C<GIGA_SUFFIX> are used by
C<format_bytes()> when the value is over 1024, 1024*1024, or
1024*1024*1024, respectively. The default values are "K", "M", and
"G". These apply in the default "traditional" mode only. Note: TERA
or higher are not implemented because of integer overflows on 32-bit
systems.
C<KIBI_SUFFIX>, C<MEBI_SUFFIX>, and C<GIBI_SUFFIX> are used by
C<format_bytes()> when the value is over 1024, 1024*1024, or
1024*1024*1024, respectively. The default values are "KiB", "MiB",
and "GiB". These apply in the "iso60027"" mode only. Note: TEBI or
higher are not implemented because of integer overflows on 32-bit
systems.
The only restrictions on C<DECIMAL_POINT> and C<THOUSANDS_SEP> are that
they must not be digits and must not be identical. There are no
restrictions on C<INT_CURR_SYMBOL>.
For example, a German user might include this in their code:
use Number::Format;
my $de = new Number::Format(-thousands_sep => '.',
-decimal_point => ',',
-int_curr_symbol => 'DEM');
my $formatted = $de->format_number($number);
Or, if you prefer not to use the object oriented interface, you can do
this instead:
use Number::Format qw(:subs :vars);
$THOUSANDS_SEP = '.';
$DECIMAL_POINT = ',';
$INT_CURR_SYMBOL = 'DEM';
my $formatted = format_number($number);
=head1 EXPORTS
Nothing is exported by default. To export the functions or the global
variables defined herein, specify the function name(s) on the import
list of the C<use Number::Format> statement. To export all functions
defined herein, use the special tag C<:subs>. To export all constants,
use the special tag C<:constants>. To export the variables, use the
special tag C<:vars>; to export subs, vars and constants
you can use the tag C<:all>.
=cut
###---------------------------------------------------------------------
use strict;
use Exporter;
use Carp;
use POSIX qw(localeconv);
use base qw(Exporter);
#
# Largest integer a 32-bit Perl can handle is based on the mantissa
# size of a double float, which is up to 53 bits. While we may be
# able to support larger values on 64-bit systems, some Perl integer
# operations on 64-bit integer systems still use the 53-bit-mantissa
# double floats. To be safe, we cap at 2**53; use Math::BigFloat
# instead for larger numbers.
#
use constant MAX_INT => 2**53;
#
# Rounding constants
use constant ROUND_ABS_FLOOR => -2;
use constant ROUND_FLOOR => -1;
use constant ROUND_NORMAL => 0;
use constant ROUND_CEIL => 1;
use constant ROUND_ABS_CEIL => 2;
our @EXPORT_SUBS =
qw( format_number format_negative format_picture
format_price format_bytes unformat_number
round floor ceil abs_floor abs_ceil );
our @EXPORT_LC_NUMERIC =
qw( $DECIMAL_POINT $THOUSANDS_SEP $GROUPING );
our @EXPORT_LC_MONETARY =
qw( $INT_CURR_SYMBOL $CURRENCY_SYMBOL $MON_DECIMAL_POINT
$MON_THOUSANDS_SEP $MON_GROUPING $POSITIVE_SIGN $NEGATIVE_SIGN
$INT_FRAC_DIGITS $FRAC_DIGITS $P_CS_PRECEDES $P_SEP_BY_SPACE
$N_CS_PRECEDES $N_SEP_BY_SPACE $P_SIGN_POSN $N_SIGN_POSN );
our @EXPORT_CONSTANTS =
qw( ROUND_ABS_FLOOR ROUND_FLOOR ROUND_NORMAL
ROUND_CEIL ROUND_ABS_CEIL );
our @EXPORT_OTHER =
qw( $DECIMAL_DIGITS $DECIMAL_FILL $NEG_FORMAT $ROUND_OPTION
$KILO_SUFFIX $MEGA_SUFFIX $GIGA_SUFFIX
$KIBI_SUFFIX $MEBI_SUFFIX $GIBI_SUFFIX );
our @EXPORT_VARS = ( @EXPORT_LC_NUMERIC, @EXPORT_LC_MONETARY, @EXPORT_OTHER );
our @EXPORT_ALL = ( @EXPORT_SUBS, @EXPORT_VARS, @EXPORT_CONSTANTS );
our @EXPORT_OK = ( @EXPORT_ALL );
our %EXPORT_TAGS = ( subs => \@EXPORT_SUBS,
vars => \@EXPORT_VARS,
constants => \@EXPORT_CONSTANTS,
lc_numeric_vars => \@EXPORT_LC_NUMERIC,
lc_monetary_vars => \@EXPORT_LC_MONETARY,
other_vars => \@EXPORT_OTHER,
all => \@EXPORT_ALL );
our $VERSION = '1.76';
# Refer to http://www.opengroup.org/onlinepubs/007908775/xbd/locale.html
# for more details about the POSIX variables
# Locale variables provided by POSIX for numbers (LC_NUMERIC)
our $DECIMAL_POINT = '.'; # decimal point symbol for numbers
our $THOUSANDS_SEP = ','; # thousands separator for numbers
our $GROUPING = undef;# grouping rules for thousands (UNSUPPORTED)
# Locale variables provided by POSIX for currency (LC_MONETARY)
our $INT_CURR_SYMBOL = 'USD';# intl currency symbol
our $CURRENCY_SYMBOL = '$'; # domestic currency symbol
our $MON_DECIMAL_POINT = '.'; # decimal point symbol for monetary values
our $MON_THOUSANDS_SEP = ','; # thousands separator for monetary values
our $MON_GROUPING = undef;# like 'grouping' for monetary (UNSUPPORTED)
our $POSITIVE_SIGN = ''; # string to add for non-negative monetary
our $NEGATIVE_SIGN = '-'; # string to add for negative monetary
our $INT_FRAC_DIGITS = 2; # digits to right of decimal for intl currency
our $FRAC_DIGITS = 2; # digits to right of decimal for currency
our $P_CS_PRECEDES = 1; # curr sym precedes(1) or follows(0) positive
our $P_SEP_BY_SPACE = 1; # add space to positive; 0, 1, or 2
our $N_CS_PRECEDES = 1; # curr sym precedes(1) or follows(0) negative
our $N_SEP_BY_SPACE = 1; # add space to negative; 0, 1, or 2
our $P_SIGN_POSN = 1; # sign rules for positive: 0-4
our $N_SIGN_POSN = 1; # sign rules for negative: 0-4
# The following are specific to Number::Format
our $DECIMAL_DIGITS = 2;
our $DECIMAL_FILL = 0;
our $NEG_FORMAT = '-x';
our $ROUND_OPTION = ROUND_NORMAL;
our $KILO_SUFFIX = 'K';
our $MEGA_SUFFIX = 'M';
our $GIGA_SUFFIX = 'G';
our $KIBI_SUFFIX = 'KiB';
our $MEBI_SUFFIX = 'MiB';
our $GIBI_SUFFIX = 'GiB';
our $DEFAULT_LOCALE = { (
# LC_NUMERIC
decimal_point => $DECIMAL_POINT,
thousands_sep => $THOUSANDS_SEP,
grouping => $GROUPING,
# LC_MONETARY
int_curr_symbol => $INT_CURR_SYMBOL,
currency_symbol => $CURRENCY_SYMBOL,
mon_decimal_point => $MON_DECIMAL_POINT,
mon_thousands_sep => $MON_THOUSANDS_SEP,
mon_grouping => $MON_GROUPING,
positive_sign => $POSITIVE_SIGN,
negative_sign => $NEGATIVE_SIGN,
int_frac_digits => $INT_FRAC_DIGITS,
frac_digits => $FRAC_DIGITS,
p_cs_precedes => $P_CS_PRECEDES,
p_sep_by_space => $P_SEP_BY_SPACE,
n_cs_precedes => $N_CS_PRECEDES,
n_sep_by_space => $N_SEP_BY_SPACE,
p_sign_posn => $P_SIGN_POSN,
n_sign_posn => $N_SIGN_POSN,
# The following are specific to Number::Format
decimal_digits => $DECIMAL_DIGITS,
decimal_fill => $DECIMAL_FILL,
neg_format => $NEG_FORMAT,
round_option => $ROUND_OPTION,
kilo_suffix => $KILO_SUFFIX,
mega_suffix => $MEGA_SUFFIX,
giga_suffix => $GIGA_SUFFIX,
kibi_suffix => $KIBI_SUFFIX,
mebi_suffix => $MEBI_SUFFIX,
gibi_suffix => $GIBI_SUFFIX,
) };
#
# On Windows, the POSIX localeconv() call returns illegal negative
# numbers for some values, seemingly attempting to indicate null. The
# following list indicates the values for which this has been
# observed, and for which the values should be stripped out of
# localeconv().
#
our @IGNORE_NEGATIVE = qw( frac_digits int_frac_digits
n_cs_precedes n_sep_by_space n_sign_posn
p_xs_precedes p_sep_by_space p_sign_posn );
###---------------------------------------------------------------------
# INTERNAL FUNCTIONS
# These functions (with names beginning with '_' are for internal use
# only. There is no guarantee that they will remain the same from one
# version to the next!
##----------------------------------------------------------------------
# _get_self creates an instance of Number::Format with the default
# values for the configuration parameters, if the first element of
# @_ is not already an object.
my $DefaultObject;
sub _get_self
{
# Not calling $_[0]->isa because that may result in unblessed
# reference error
unless (ref $_[0] && UNIVERSAL::isa($_[0], "Number::Format"))
{
$DefaultObject ||= new Number::Format();
unshift (@_, $DefaultObject);
}
@_;
}
##----------------------------------------------------------------------
# _check_seps is used to validate that the thousands_sep,
# decimal_point, mon_thousands_sep and mon_decimal_point variables
# have acceptable values. For internal use only.
sub _check_seps
{
my ($self) = @_;
croak "Not an object" unless ref $self;
foreach my $prefix ("", "mon_")
{
croak "${prefix}thousands_sep is undefined"
unless defined $self->{"${prefix}thousands_sep"};
croak "${prefix}thousands_sep may not be numeric"
if $self->{"${prefix}thousands_sep"} =~ /\d/;
croak "${prefix}decimal_point may not be numeric"
if $self->{"${prefix}decimal_point"} =~ /\d/;
croak("${prefix}thousands_sep and ".
"${prefix}decimal_point may not be equal")
if $self->{"${prefix}decimal_point"} eq
$self->{"${prefix}thousands_sep"};
}
}
##----------------------------------------------------------------------
# _get_multipliers returns the multipliers to be used for kilo, mega,
# and giga (un-)formatting. Used in format_bytes and unformat_number.
# For internal use only.
sub _get_multipliers
{
my($base) = @_;
if (!defined($base) || $base == 1024)
{
return ( kilo => 0x00000400,
mega => 0x00100000,
giga => 0x40000000 );
}
elsif ($base == 1000)
{
return ( kilo => 1_000,
mega => 1_000_000,
giga => 1_000_000_000 );
}
else
{
croak "base overflow" if $base **3 > MAX_INT;
croak "base must be a positive integer"
unless $base > 0 && $base == int($base);
return ( kilo => $base,
mega => $base ** 2,
giga => $base ** 3 );
}
}
##----------------------------------------------------------------------
# _complain_undef displays a warning message on STDERR and is called
# when a subroutine has been invoked with an undef value. A warning
# message is printed if the calling environment has "uninitialized"
# warnings enabled.
sub _complain_undef
{
my @stack;
my($sub) = (caller(1))[3];
carp "Use of uninitialized value in call to $sub"
if warnings::enabled("uninitialized");
}
###---------------------------------------------------------------------
=head1 METHODS
=over 4
=cut
##----------------------------------------------------------------------
=item new( %args )
Creates a new Number::Format object. Valid keys for %args are any of
the parameters described above. Keys may be in all uppercase or all
lowercase, and may optionally be preceded by a hyphen (-) character.
Example:
my $de = new Number::Format(-thousands_sep => '.',
-decimal_point => ',',
-int_curr_symbol => 'DEM');
=cut
sub new
{
my $type = shift;
my %args = @_;
# Fetch defaults from current locale, or failing that, using globals
my $me = {};
# my $locale = setlocale(LC_ALL, "");
my $locale_values = localeconv();
# Strip out illegal negative values from the current locale
foreach ( @IGNORE_NEGATIVE )
{
if (defined($locale_values->{$_}) && $locale_values->{$_} eq '-1')
{
delete $locale_values->{$_};
}
}
while(my($arg, $default) = each %$DEFAULT_LOCALE)
{
$me->{$arg} = (exists $locale_values->{$arg}
? $locale_values->{$arg}
: $default);
foreach ($arg, uc $arg, "-$arg", uc "-$arg")
{
next unless defined $args{$_};
$me->{$arg} = $args{$_};
delete $args{$_};
last;
}
}
#
# Some broken locales define the decimal_point but not the
# thousands_sep. If decimal_point is set to "," the default
# thousands_sep will be a conflict. In that case, set
# thousands_sep to empty string. Suggested by Moritz Onken.
#
foreach my $prefix ("", "mon_")
{
$me->{"${prefix}thousands_sep"} = ""
if ($me->{"${prefix}decimal_point"} eq
$me->{"${prefix}thousands_sep"});
}
croak "Invalid argument(s)" if %args;
bless $me, $type;
$me;
}
##----------------------------------------------------------------------
=item round($number, $precision, $roundoption)
Rounds the number to the specified precision. If C<$precision> is
omitted, the value of the C<DECIMAL_DIGITS> parameter is used (default
value 2). Both input and output are numeric (the function uses math
operators rather than string manipulation to do its job), The value
of C<$precision> may be any integer, positive or negative. If
C<$roundoption> is omitted, the value of the C<ROUND_OPTION> paramter is
used (default value C<ROUND_NORMAL>). Passing undef as a value for
C<$precision> or C<$roundoption> will preserve the default behavior.
Examples:
round(3.14159) yields 3.14
round(3.14159, undef, ROUND_CEIL) yields 3.15
round(3.14159, undef, ROUND_FLOOR) yields 3.14
round(3.14159, 4) yields 3.1416
round(42.00, 4) yields 42
round(1234, -2) yields 1200
round(1234, -2, ROUND_CEIL) yields 1300
round(1298, -2) yields 1300
round(1298, -2, ROUND_FLOOR) yields 1200
Since this is a mathematical rather than string oriented function,
there will be no trailing zeroes to the right of the decimal point,
and the C<DECIMAL_POINT> and C<THOUSANDS_SEP> variables are ignored.
To format your number using the C<DECIMAL_POINT> and C<THOUSANDS_SEP>
variables, use C<format_number()> instead.
=cut
sub round
{
my ($self, $number, $precision, $roundoption) = _get_self @_;
unless (defined($number))
{
_complain_undef();
$number = 0;
}
$precision = $self->{decimal_digits} unless defined $precision;
$precision = 2 unless defined $precision;
$roundoption = $self->{round_option} unless defined $roundoption;
$roundoption = ROUND_NORMAL unless defined $roundoption;
croak("precision must be integer")
unless int($precision) == $precision;
if (ref($number) && $number->isa("Math::BigFloat"))
{
my $rounded = $number->copy();
if ($roundoption) {
$rounded *= 10**$precision;
if (
$roundoption == ROUND_FLOOR
or ($roundoption == ROUND_ABS_FLOOR and not $rounded->is_neg())
or ($roundoption == ROUND_ABS_CEIL and $rounded->is_neg())
) {
$rounded->bfloor();
}
elsif (
$roundoption == ROUND_CEIL
or ($roundoption == ROUND_ABS_CEIL and not $rounded->is_neg())
or ($roundoption == ROUND_ABS_FLOOR and $rounded->is_neg())
) {
$rounded->bceil();
}
else {
croak "round() called with invalid roundoption"
}
$rounded /= 10**$precision;
}
$rounded->round(0, -$precision);
return $rounded;
}
my $sign = $number <=> 0;
my $multiplier = (10 ** $precision);
my $result = abs($number);
my $product = $result * $multiplier;
croak "round() overflow. Try smaller precision or use Math::BigFloat"
if $product > MAX_INT;
# We need to add 1e-14 to avoid some rounding errors due to the
# way floating point numbers work - see string-eq test in t/round.t
if (
$roundoption == ROUND_FLOOR
or ($roundoption == ROUND_ABS_FLOOR and $sign >= 0)
or ($roundoption == ROUND_ABS_CEIL and $sign < 0)
) {
if ($sign < 0) {
$result = int($product + 1 - 1e-14) / -$multiplier;
}
else {
$result = int($product) / $multiplier;
}
}
elsif ($roundoption == ROUND_NORMAL) {
if ($sign < 0) {
$result = int($product + 0.5 + 1e-14) / -$multiplier;
}
else {
$result = int($product + 0.5 + 1e-14) / $multiplier;
}
}
elsif (
$roundoption == ROUND_CEIL
or ($roundoption == ROUND_ABS_CEIL and $sign >= 0)
or ($roundoption == ROUND_ABS_FLOOR and $sign < 0)
) {
if ($sign < 0) {
$result = int($product) / -$multiplier;
}
else {
$result = int($product + 1 - 1e-14) / $multiplier;
}
}
else {
croak "round() called with invalid roundoption"
}
return $result;
}
##----------------------------------------------------------------------
=item floor($number, $precision)
Floors the number to the specified precision.
floor(3.14159) yields 3
floor(3.14159, 2) yields 3.14
floor(-42.5) yields -43
=cut
sub floor
{
my ($self, $number, $precision) = _get_self @_;
return $self->round($number, $precision, ROUND_FLOOR);
}
##----------------------------------------------------------------------
=item abs_floor($number, $precision)
Floors the absolute number to the specified precision.
abs_floor(3.14159) yields 3
abs_floor(3.14159, 2) yields 3.14
abs_floor(-42.5) yields -42
=cut
sub abs_floor
{
my ($self, $number, $precision) = _get_self @_;
return $self->round($number, $precision, ROUND_ABS_FLOOR);
}
##----------------------------------------------------------------------
=item ceil($number, $precision)
Ceils the number to the specified precision.
ceil(3.14159) yields 4
ceil(3.14159, 2) yields 3.15
ceil(-42.5) yields -42
=cut
sub ceil
{
my ($self, $number, $precision) = _get_self @_;
return $self->round($number, $precision, ROUND_CEIL);
}
##----------------------------------------------------------------------
=item abs_ceil($number, $precision)
Ceils the absolue number to the specified precision.
ceil(3.14159) yields 4
ceil(3.14159, 2) yields 3.15
ceil(-42.5) yields -4e
=cut
sub abs_ceil
{
my ($self, $number, $precision) = _get_self @_;
return $self->round($number, $precision, ROUND_ABS_CEIL);
}
##----------------------------------------------------------------------
=item format_number($number, $precision, $trailing_zeroes, $mon, $roundoption)
Formats a number by adding C<THOUSANDS_SEP> between each set of 3
digits to the left of the decimal point, substituting C<DECIMAL_POINT>
for the decimal point, and rounding to the specified precision using
C<round()>. Note that C<$precision> is a I<maximum> precision
specifier; trailing zeroes will only appear in the output if
C<$trailing_zeroes> is provided, or the parameter C<DECIMAL_FILL> is
set, with a value that is true (not zero, undef, or the empty string).
If C<$precision> is omitted, the value of the C<DECIMAL_DIGITS>
parameter (default value of 2) is used. If C<$mon> is true (default
value false) the monetary separators are used. C<$precision> and
C<$roundoption> are direct passed to C<round()>. Passing undef as a
value for C<$precision>, C<$trailing_zeroes>, C<$mon> or C<$roundoption>
will preserve the default behavior.
If the value is too large or great to work with as a regular number,
but instead must be shown in scientific notation, returns that number
in scientific notation without further formatting.
Examples:
format_number(12345.6789) yields '12,345.68'
format_number(123456.789, 2) yields '123,456.79'
format_number(1234567.89, 2) yields '1,234,567.89'
format_number(1234567.8, 2) yields '1,234,567.8'
format_number(1234567.8, 2, 1) yields '1,234,567.80'
format_number(1.23456789, 6) yields '1.234568'
format_number("0.000020000E+00", 7); yields '2e-05'
format_number(1.3579, 2, undef, undef, ROUND_FLOOR) yields '1.35'
Of course the output would have your values of C<THOUSANDS_SEP> and
C<DECIMAL_POINT> instead of ',' and '.' respectively.
=cut
sub format_number
{
my ($self, $number, $precision, $trailing_zeroes, $mon, $roundoption) = _get_self @_;
unless (defined($number))
{
_complain_undef();
$number = 0;
}
$self->_check_seps(); # first make sure the SEP variables are valid
my($thousands_sep, $decimal_point) =
$mon ? @$self{qw(mon_thousands_sep mon_decimal_point)}
: @$self{qw(thousands_sep decimal_point)};
# Set defaults and standardize number
$precision = $self->{decimal_digits} unless defined $precision;
$trailing_zeroes = $self->{decimal_fill} unless defined $trailing_zeroes;
# Handle negative numbers
my $sign = $number <=> 0;
$number = $self->round($number, $precision, $roundoption); # round off $number
$number = abs($number) if $sign < 0;
# detect scientific notation
my $exponent = 0;
if ($number =~ /^(-?[\d.]+)e([+-]\d+)$/)
{
# Don't attempt to format numbers that require scientific notation.
return $number;
}
# Split integer and decimal parts of the number and add commas
my $integer = int($number);
my $decimal;
# Note: In perl 5.6 and up, string representation of a number
# automagically includes the locale decimal point. This way we
# will detect the decimal part correctly as long as the decimal
# point is 1 character.
$decimal = substr($number, length($integer)+1)
if (length($integer) < length($number));
$decimal = '' unless defined $decimal;
# Add trailing 0's if $trailing_zeroes is set.
$decimal .= '0'x( $precision - length($decimal) )
if $trailing_zeroes && $precision > length($decimal);
# Add the commas (or whatever is in thousands_sep). If
# thousands_sep is the empty string, do nothing.
if ($thousands_sep)
{
# Add leading 0's so length($integer) is divisible by 3
$integer = '0'x(3 - (length($integer) % 3)).$integer;
# Split $integer into groups of 3 characters and insert commas
$integer = join($thousands_sep,
grep {$_ ne ''} split(/(...)/, $integer));
# Strip off leading zeroes and optional thousands separator
$integer =~ s/^0+(?:\Q$thousands_sep\E)?//;
}
$integer = '0' if $integer eq '';
# Combine integer and decimal parts and return the result.
my $result = ((defined $decimal && length $decimal) ?
join($decimal_point, $integer, $decimal) :
$integer);
return ($sign < 0) ? $self->format_negative($result) : $result;
}
##----------------------------------------------------------------------
=item format_negative($number, $picture)
Formats a negative number. Picture should be a string that contains
the letter C<x> where the number should be inserted. For example, for
standard negative numbers you might use ``C<-x>'', while for
accounting purposes you might use ``C<(x)>''. If the specified number
begins with a ``-'' character, that will be removed before formatting,
but formatting will occur whether or not the number is negative.
=cut
sub format_negative
{
my($self, $number, $format) = _get_self @_;
unless (defined($number))
{
_complain_undef();
$number = 0;
}
$format = $self->{neg_format} unless defined $format;
croak "Letter x must be present in picture in format_negative()"
unless $format =~ /x/;
$number =~ s/^-//;
$format =~ s/x/$number/;
return $format;
}
##----------------------------------------------------------------------
=item format_picture($number, $picture)
Returns a string based on C<$picture> with the C<#> characters
replaced by digits from C<$number>. If the length of the integer part
of $number is too large to fit, the C<#> characters are replaced with
asterisks (C<*>) instead. Examples:
format_picture(100.023, 'USD ##,###.##') yields 'USD 100.02'
format_picture(1000.23, 'USD ##,###.##') yields 'USD 1,000.23'
format_picture(10002.3, 'USD ##,###.##') yields 'USD 10,002.30'
format_picture(100023, 'USD ##,###.##') yields 'USD **,***.**'
format_picture(1.00023, 'USD #.###,###') yields 'USD 1.002,300'
The comma (,) and period (.) you see in the picture examples should
match the values of C<THOUSANDS_SEP> and C<DECIMAL_POINT>,
respectively, for proper operation. However, the C<THOUSANDS_SEP>
characters in C<$picture> need not occur every three digits; the
I<only> use of that variable by this function is to remove leading
commas (see the first example above). There may not be more than one
instance of C<DECIMAL_POINT> in C<$picture>.
The value of C<NEG_FORMAT> is used to determine how negative numbers
are displayed. The result of this is that the output of this function
my have unexpected spaces before and/or after the number. This is
necessary so that positive and negative numbers are formatted into a
space the same size. If you are only using positive numbers and want
to avoid this problem, set NEG_FORMAT to "x".
=cut
sub format_picture
{
my ($self, $number, $picture) = _get_self @_;
unless (defined($number))
{
_complain_undef();
$number = 0;
}
croak "Picture not defined" unless defined($picture);
$self->_check_seps();
# Handle negative numbers
my($neg_prefix) = $self->{neg_format} =~ /^([^x]*)/;
my($pic_prefix) = $picture =~ /^([^\#]+)/;
my $neg_pic = $self->{neg_format};
(my $pos_pic = $self->{neg_format}) =~ s/[^x\s]/ /g;
(my $pos_prefix = $neg_prefix) =~ s/[^x\s]/ /g;
$neg_pic =~ s/x/$picture/;
$pos_pic =~ s/x/$picture/;
my $sign = $number <=> 0;
$number = abs($number) if $sign < 0;
$picture = $sign < 0 ? $neg_pic : $pos_pic;
my $sign_prefix = $sign < 0 ? $neg_prefix : $pos_prefix;
# Split up the picture and die if there is more than one $DECIMAL_POINT
my($pic_int, $pic_dec, @cruft) =
split(/\Q$self->{decimal_point}\E/, $picture);
$pic_int = '' unless defined $pic_int;
$pic_dec = '' unless defined $pic_dec;
croak "Only one decimal separator permitted in picture"
if @cruft;
# Obtain precision from the length of the decimal part...
my $precision = $pic_dec; # start with copying it
$precision =~ s/[^\#]//g; # eliminate all non-# characters
$precision = length $precision; # take the length of the result
# Format the number
$number = $self->round($number, $precision);
# Obtain the length of the integer portion just like we did for $precision
my $intsize = $pic_int; # start with copying it
$intsize =~ s/[^\#]//g; # eliminate all non-# characters
$intsize = length $intsize; # take the length of the result
# Split up $number same as we did for $picture earlier
my($num_int, $num_dec) = split(/\./, $number, 2);
$num_int = '' unless defined $num_int;
$num_dec = '' unless defined $num_dec;
# Check if the integer part will fit in the picture
if (length $num_int > $intsize)
{
$picture =~ s/\#/\*/g; # convert # to * and return it
$pic_prefix = "" unless defined $pic_prefix;
$picture =~ s/^(\Q$sign_prefix\E)(\Q$pic_prefix\E)(\s*)/$2$3$1/;
return $picture;
}
# Split each portion of number and picture into arrays of characters
my @num_int = split(//, $num_int);
my @num_dec = split(//, $num_dec);
my @pic_int = split(//, $pic_int);
my @pic_dec = split(//, $pic_dec);
# Now we copy those characters into @result.
my @result;
@result = ($self->{decimal_point})
if $picture =~ /\Q$self->{decimal_point}\E/;
# For each characture in the decimal part of the picture, replace '#'
# signs with digits from the number.
my $char;
foreach $char (@pic_dec)
{
$char = (shift(@num_dec) || 0) if ($char eq '#');
push (@result, $char);
}
# For each character in the integer part of the picture (moving right
# to left this time), replace '#' signs with digits from the number,
# or spaces if we've run out of numbers.
while ($char = pop @pic_int)
{
$char = pop(@num_int) if ($char eq '#');
$char = ' ' if (!defined($char) ||
$char eq $self->{thousands_sep} && $#num_int < 0);
unshift (@result, $char);
}
# Combine @result into a string and return it.
my $result = join('', @result);
$sign_prefix = '' unless defined $sign_prefix;
$pic_prefix = '' unless defined $pic_prefix;
$result =~ s/^(\Q$sign_prefix\E)(\Q$pic_prefix\E)(\s*)/$2$3$1/;
$result;
}
##----------------------------------------------------------------------
=item format_price($number, $precision, $symbol)
Returns a string containing C<$number> formatted similarly to
C<format_number()>, except that the decimal portion may have trailing
zeroes added to make it be exactly C<$precision> characters long, and
the currency string will be prefixed.
The C<$symbol> attribute may be one of "INT_CURR_SYMBOL" or