File Coverage

blib/lib/Number/Format.pm
Criterion Covered Total %
statement 281 293 95.9
branch 180 218 82.5
condition 41 64 64.0
subroutine 20 20 100.0
pod 8 8 100.0
total 530 603 87.8


line stmt bran cond sub pod time code
1             package Number::Format;
2              
3             # Minimum version is 5.10.0. May work on earlier versions, but not
4             # supported on any version older than 5.10. Hack this line at your own risk:
5             require 5.010;
6              
7 9     9   689321 use strict;
  9         84  
  9         258  
8 9     9   44 use warnings;
  9         18  
  9         404  
9              
10             =head1 NAME
11              
12             Number::Format - Perl extension for formatting numbers
13              
14             =head1 SYNOPSIS
15              
16             use Number::Format;
17             my $x = new Number::Format %args;
18             $formatted = $x->round($number, $precision);
19             $formatted = $x->format_number($number, $precision, $trailing_zeroes);
20             $formatted = $x->format_negative($number, $picture);
21             $formatted = $x->format_picture($number, $picture);
22             $formatted = $x->format_price($number, $precision, $symbol);
23             $formatted = $x->format_bytes($number, $precision);
24             $number = $x->unformat_number($formatted);
25              
26             use Number::Format qw(:subs);
27             $formatted = round($number, $precision);
28             $formatted = format_number($number, $precision, $trailing_zeroes);
29             $formatted = format_negative($number, $picture);
30             $formatted = format_picture($number, $picture);
31             $formatted = format_price($number, $precision, $symbol);
32             $formatted = format_bytes($number, $precision);
33             $number = unformat_number($formatted);
34              
35             =head1 REQUIRES
36              
37             Perl, version 5.8 or higher.
38              
39             POSIX.pm to determine locale settings.
40              
41             Carp.pm is used for some error reporting.
42              
43             =head1 DESCRIPTION
44              
45             These functions provide an easy means of formatting numbers in a
46             manner suitable for displaying to the user.
47              
48             There are two ways to use this package. One is to declare an object
49             of type Number::Format, which you can think of as a formatting engine.
50             The various functions defined here are provided as object methods.
51             The constructor C can be used to set the parameters of the
52             formatting engine. Valid parameters are:
53              
54             THOUSANDS_SEP - character inserted between groups of 3 digits
55             DECIMAL_POINT - character separating integer and fractional parts
56             MON_THOUSANDS_SEP - like THOUSANDS_SEP, but used for format_price
57             MON_DECIMAL_POINT - like DECIMAL_POINT, but used for format_price
58             INT_CURR_SYMBOL - character(s) denoting currency (see format_price())
59             DECIMAL_DIGITS - number of digits to the right of dec point (def 2)
60             DECIMAL_FILL - boolean; whether to add zeroes to fill out decimal
61             NEG_FORMAT - format to display negative numbers (def ``-x'')
62             KILO_SUFFIX - suffix to add when format_bytes formats kilobytes (trad)
63             MEGA_SUFFIX - " " " " " " megabytes (trad)
64             GIGA_SUFFIX - " " " " " " gigabytes (trad)
65             KIBI_SUFFIX - suffix to add when format_bytes formats kibibytes (iec)
66             MEBI_SUFFIX - " " " " " " mebibytes (iec)
67             GIBI_SUFFIX - " " " " " " gibibytes (iec)
68              
69             They may be specified in upper or lower case, with or without a
70             leading hyphen ( - ).
71              
72             If C is set to the empty string, format_number will not
73             insert any separators.
74              
75             The defaults for C, C,
76             C, C, and C
77             come from the POSIX locale information (see L). If your
78             POSIX locale does not provide C and/or
79             C fields, then the C and/or
80             C values are used for those parameters. Formerly,
81             POSIX was optional but this caused problems in some cases, so it is
82             now required. If this causes you hardship, please contact the author
83             of this package at (remove "SPAM" to get correct
84             email address) for help.
85              
86             If any of the above parameters are not specified when you invoke
87             C, then the values are taken from package global variables of
88             the same name (e.g. C<$DECIMAL_POINT> is the default for the
89             C parameter). If you use the C<:vars> keyword on your
90             C line (see non-object-oriented example below) you
91             will import those variables into your namesapce and can assign values
92             as if they were your own local variables. The default values for all
93             the parameters are:
94              
95             THOUSANDS_SEP = ','
96             DECIMAL_POINT = '.'
97             MON_THOUSANDS_SEP = ','
98             MON_DECIMAL_POINT = '.'
99             INT_CURR_SYMBOL = 'USD'
100             DECIMAL_DIGITS = 2
101             DECIMAL_FILL = 0
102             NEG_FORMAT = '-x'
103             KILO_SUFFIX = 'K'
104             MEGA_SUFFIX = 'M'
105             GIGA_SUFFIX = 'G'
106             KIBI_SUFFIX = 'KiB'
107             MEBI_SUFFIX = 'MiB'
108             GIBI_SUFFIX = 'GiB'
109              
110             Note however that when you first call one of the functions in this
111             module I using the object-oriented interface, further setting
112             of those global variables will have no effect on non-OO calls. It is
113             recommended that you use the object-oriented interface instead for
114             fewer headaches and a cleaner design.
115              
116             The C and C values are not set by the
117             Locale system, but are definable by the user. They affect the output
118             of C. Setting C is like giving that
119             value as the C<$precision> argument to that function. Setting
120             C to a true value causes C to append
121             zeroes to the right of the decimal digits until the length is the
122             specified number of digits.
123              
124             C is only used by C and is a string
125             containing the letter 'x', where that letter will be replaced by a
126             positive representation of the number being passed to that function.
127             C and C utilize this feature by
128             calling C if the number was less than 0.
129              
130             C, C, and C are used by
131             C when the value is over 1024, 1024*1024, or
132             1024*1024*1024, respectively. The default values are "K", "M", and
133             "G". These apply in the default "traditional" mode only. Note: TERA
134             or higher are not implemented because of integer overflows on 32-bit
135             systems.
136              
137             C, C, and C are used by
138             C when the value is over 1024, 1024*1024, or
139             1024*1024*1024, respectively. The default values are "KiB", "MiB",
140             and "GiB". These apply in the "iso60027"" mode only. Note: TEBI or
141             higher are not implemented because of integer overflows on 32-bit
142             systems.
143              
144             The only restrictions on C and C are that
145             they must not be digits and must not be identical. There are no
146             restrictions on C.
147              
148             For example, a German user might include this in their code:
149              
150             use Number::Format;
151             my $de = new Number::Format(-thousands_sep => '.',
152             -decimal_point => ',',
153             -int_curr_symbol => 'DEM');
154             my $formatted = $de->format_number($number);
155              
156             Or, if you prefer not to use the object oriented interface, you can do
157             this instead:
158              
159             use Number::Format qw(:subs :vars);
160             $THOUSANDS_SEP = '.';
161             $DECIMAL_POINT = ',';
162             $INT_CURR_SYMBOL = 'DEM';
163             my $formatted = format_number($number);
164              
165             =head1 EXPORTS
166              
167             Nothing is exported by default. To export the functions or the global
168             variables defined herein, specify the function name(s) on the import
169             list of the C statement. To export all functions
170             defined herein, use the special tag C<:subs>. To export the
171             variables, use the special tag C<:vars>; to export both subs and vars
172             you can use the tag C<:all>.
173              
174             =cut
175              
176             ###---------------------------------------------------------------------
177              
178 9     9   46 use strict;
  9         14  
  9         137  
179 9     9   38 use Exporter;
  9         16  
  9         346  
180 9     9   57 use Carp;
  9         17  
  9         526  
181 9     9   554 use POSIX qw(localeconv);
  9         6887  
  9         48  
182 9     9   4051 use base qw(Exporter);
  9         17  
  9         6479  
183              
184             our @EXPORT_SUBS =
185             qw( format_number format_negative format_picture
186             format_price format_bytes round unformat_number );
187              
188             our @EXPORT_LC_NUMERIC =
189             qw( $DECIMAL_POINT $THOUSANDS_SEP $GROUPING );
190              
191             our @EXPORT_LC_MONETARY =
192             qw( $INT_CURR_SYMBOL $CURRENCY_SYMBOL $MON_DECIMAL_POINT
193             $MON_THOUSANDS_SEP $MON_GROUPING $POSITIVE_SIGN $NEGATIVE_SIGN
194             $INT_FRAC_DIGITS $FRAC_DIGITS $P_CS_PRECEDES $P_SEP_BY_SPACE
195             $N_CS_PRECEDES $N_SEP_BY_SPACE $P_SIGN_POSN $N_SIGN_POSN );
196              
197             our @EXPORT_OTHER =
198             qw( $DECIMAL_DIGITS $DECIMAL_FILL $NEG_FORMAT
199             $KILO_SUFFIX $MEGA_SUFFIX $GIGA_SUFFIX
200             $KIBI_SUFFIX $MEBI_SUFFIX $GIBI_SUFFIX );
201              
202             our @EXPORT_VARS = ( @EXPORT_LC_NUMERIC, @EXPORT_LC_MONETARY, @EXPORT_OTHER );
203             our @EXPORT_ALL = ( @EXPORT_SUBS, @EXPORT_VARS );
204              
205             our @EXPORT_OK = ( @EXPORT_ALL );
206              
207             our %EXPORT_TAGS = ( subs => \@EXPORT_SUBS,
208             vars => \@EXPORT_VARS,
209             lc_numeric_vars => \@EXPORT_LC_NUMERIC,
210             lc_monetary_vars => \@EXPORT_LC_MONETARY,
211             other_vars => \@EXPORT_OTHER,
212             all => \@EXPORT_ALL );
213              
214             our $VERSION = '1.76';
215              
216             # Refer to http://www.opengroup.org/onlinepubs/007908775/xbd/locale.html
217             # for more details about the POSIX variables
218              
219             # Locale variables provided by POSIX for numbers (LC_NUMERIC)
220             our $DECIMAL_POINT = '.'; # decimal point symbol for numbers
221             our $THOUSANDS_SEP = ','; # thousands separator for numbers
222             our $GROUPING = undef;# grouping rules for thousands (UNSUPPORTED)
223              
224             # Locale variables provided by POSIX for currency (LC_MONETARY)
225             our $INT_CURR_SYMBOL = 'USD';# intl currency symbol
226             our $CURRENCY_SYMBOL = '$'; # domestic currency symbol
227             our $MON_DECIMAL_POINT = '.'; # decimal point symbol for monetary values
228             our $MON_THOUSANDS_SEP = ','; # thousands separator for monetary values
229             our $MON_GROUPING = undef;# like 'grouping' for monetary (UNSUPPORTED)
230             our $POSITIVE_SIGN = ''; # string to add for non-negative monetary
231             our $NEGATIVE_SIGN = '-'; # string to add for negative monetary
232             our $INT_FRAC_DIGITS = 2; # digits to right of decimal for intl currency
233             our $FRAC_DIGITS = 2; # digits to right of decimal for currency
234             our $P_CS_PRECEDES = 1; # curr sym precedes(1) or follows(0) positive
235             our $P_SEP_BY_SPACE = 1; # add space to positive; 0, 1, or 2
236             our $N_CS_PRECEDES = 1; # curr sym precedes(1) or follows(0) negative
237             our $N_SEP_BY_SPACE = 1; # add space to negative; 0, 1, or 2
238             our $P_SIGN_POSN = 1; # sign rules for positive: 0-4
239             our $N_SIGN_POSN = 1; # sign rules for negative: 0-4
240              
241             # The following are specific to Number::Format
242             our $DECIMAL_DIGITS = 2;
243             our $DECIMAL_FILL = 0;
244             our $NEG_FORMAT = '-x';
245             our $KILO_SUFFIX = 'K';
246             our $MEGA_SUFFIX = 'M';
247             our $GIGA_SUFFIX = 'G';
248             our $KIBI_SUFFIX = 'KiB';
249             our $MEBI_SUFFIX = 'MiB';
250             our $GIBI_SUFFIX = 'GiB';
251              
252             our $DEFAULT_LOCALE = { (
253             # LC_NUMERIC
254             decimal_point => $DECIMAL_POINT,
255             thousands_sep => $THOUSANDS_SEP,
256             grouping => $GROUPING,
257              
258             # LC_MONETARY
259             int_curr_symbol => $INT_CURR_SYMBOL,
260             currency_symbol => $CURRENCY_SYMBOL,
261             mon_decimal_point => $MON_DECIMAL_POINT,
262             mon_thousands_sep => $MON_THOUSANDS_SEP,
263             mon_grouping => $MON_GROUPING,
264             positive_sign => $POSITIVE_SIGN,
265             negative_sign => $NEGATIVE_SIGN,
266             int_frac_digits => $INT_FRAC_DIGITS,
267             frac_digits => $FRAC_DIGITS,
268             p_cs_precedes => $P_CS_PRECEDES,
269             p_sep_by_space => $P_SEP_BY_SPACE,
270             n_cs_precedes => $N_CS_PRECEDES,
271             n_sep_by_space => $N_SEP_BY_SPACE,
272             p_sign_posn => $P_SIGN_POSN,
273             n_sign_posn => $N_SIGN_POSN,
274              
275             # The following are specific to Number::Format
276             decimal_digits => $DECIMAL_DIGITS,
277             decimal_fill => $DECIMAL_FILL,
278             neg_format => $NEG_FORMAT,
279             kilo_suffix => $KILO_SUFFIX,
280             mega_suffix => $MEGA_SUFFIX,
281             giga_suffix => $GIGA_SUFFIX,
282             kibi_suffix => $KIBI_SUFFIX,
283             mebi_suffix => $MEBI_SUFFIX,
284             gibi_suffix => $GIBI_SUFFIX,
285             ) };
286              
287             #
288             # POSIX::localeconv() returns -1 for numeric values that are not applicable to
289             # the current locale. This module ignores them. @IGNORE_NEGATIVE lists the
290             # ones that this module otherwise handles (there are some fields that this
291             # module always ignores, so don't need to be in the list). (Prior to v5.37.7,
292             # only the Windows version of POSIX::localeconv() returned -1; other versions
293             # simply didn't return any values at all for not-applicable fields. But the
294             # end result is the same regardless of version.)
295              
296             #
297             our @IGNORE_NEGATIVE = qw( frac_digits int_frac_digits
298             n_cs_precedes n_sep_by_space n_sign_posn
299             p_xs_precedes p_sep_by_space p_sign_posn );
300              
301             #
302             # Largest integer a 32-bit Perl can handle is based on the mantissa
303             # size of a double float, which is up to 53 bits. While we may be
304             # able to support larger values on 64-bit systems, some Perl integer
305             # operations on 64-bit integer systems still use the 53-bit-mantissa
306             # double floats. To be safe, we cap at 2**53; use Math::BigFloat
307             # instead for larger numbers.
308             #
309 9     9   82 use constant MAX_INT => 2**53;
  9         27  
  9         35134  
310              
311             ###---------------------------------------------------------------------
312              
313             # INTERNAL FUNCTIONS
314              
315             # These functions (with names beginning with '_' are for internal use
316             # only. There is no guarantee that they will remain the same from one
317             # version to the next!
318              
319             ##----------------------------------------------------------------------
320              
321             # _get_self creates an instance of Number::Format with the default
322             # values for the configuration parameters, if the first element of
323             # @_ is not already an object.
324              
325             my $DefaultObject;
326             sub _get_self
327             {
328             # Not calling $_[0]->isa because that may result in unblessed
329             # reference error
330 327 100 66 327   1337 unless (ref $_[0] && UNIVERSAL::isa($_[0], "Number::Format"))
331             {
332 63   66     160 $DefaultObject ||= new Number::Format();
333 63         145 unshift (@_, $DefaultObject);
334             }
335 327         855 @_;
336             }
337              
338             ##----------------------------------------------------------------------
339              
340             # _check_seps is used to validate that the thousands_sep,
341             # decimal_point, mon_thousands_sep and mon_decimal_point variables
342             # have acceptable values. For internal use only.
343              
344             sub _check_seps
345             {
346 125     125   194 my ($self) = @_;
347 125 50       264 croak "Not an object" unless ref $self;
348 125         228 foreach my $prefix ("", "mon_")
349             {
350             croak "${prefix}thousands_sep is undefined"
351 250 50       556 unless defined $self->{"${prefix}thousands_sep"};
352             croak "${prefix}thousands_sep may not be numeric"
353 250 50       711 if $self->{"${prefix}thousands_sep"} =~ /\d/;
354             croak "${prefix}decimal_point may not be numeric"
355 250 50       587 if $self->{"${prefix}decimal_point"} =~ /\d/;
356             croak("${prefix}thousands_sep and ".
357             "${prefix}decimal_point may not be equal")
358             if $self->{"${prefix}decimal_point"} eq
359             $self->{"${prefix}thousands_sep"}
360              
361             # There are legal locales where 'mon_decimal_point' and
362             # 'mon_thousands_sep' are both "" (the empty string)
363 250 0 0     725 && ($prefix eq "" || $self->{"mon_decimal_point"} ne "");
      33        
364             }
365             }
366              
367             ##----------------------------------------------------------------------
368              
369             # _get_multipliers returns the multipliers to be used for kilo, mega,
370             # and giga (un-)formatting. Used in format_bytes and unformat_number.
371             # For internal use only.
372              
373             sub _get_multipliers
374             {
375 36     36   94 my($base) = @_;
376 36 100 100     143 if (!defined($base) || $base == 1024)
    100          
377             {
378 29         122 return ( kilo => 0x00000400,
379             mega => 0x00100000,
380             giga => 0x40000000 );
381             }
382             elsif ($base == 1000)
383             {
384 2         7 return ( kilo => 1_000,
385             mega => 1_000_000,
386             giga => 1_000_000_000 );
387             }
388             else
389             {
390 5 100       233 croak "base overflow" if $base **3 > MAX_INT;
391 4 100 100     339 croak "base must be a positive integer"
392             unless $base > 0 && $base == int($base);
393 1         5 return ( kilo => $base,
394             mega => $base ** 2,
395             giga => $base ** 3 );
396             }
397             }
398              
399             ##----------------------------------------------------------------------
400              
401             # _complain_undef displays a warning message on STDERR and is called
402             # when a subroutine has been invoked with an undef value. A warning
403             # message is printed if the calling environment has "uninitialized"
404             # warnings enabled.
405              
406             sub _complain_undef
407             {
408 8     8   19 my @stack;
409 8         63 my($sub, $bitmask) = (caller(1))[3,9];
410 8         27 my $offset = $warnings::Offsets{"uninitialized"};
411 8 100       1225 carp "Use of uninitialized value in call to $sub"
412             if vec($bitmask, $offset, 1);
413             }
414              
415              
416             ###---------------------------------------------------------------------
417              
418             =head1 METHODS
419              
420             =over 4
421              
422             =cut
423              
424             ##----------------------------------------------------------------------
425              
426             =item new( %args )
427              
428             Creates a new Number::Format object. Valid keys for %args are any of
429             the parameters described above. Keys may be in all uppercase or all
430             lowercase, and may optionally be preceded by a hyphen (-) character.
431             Example:
432              
433             my $de = new Number::Format(-thousands_sep => '.',
434             -decimal_point => ',',
435             -int_curr_symbol => 'DEM');
436              
437             =cut
438              
439             sub new
440             {
441 12     12 1 3204 my $type = shift;
442 12         59 my %args = @_;
443              
444             # Fetch defaults from current locale, or failing that, using globals
445 12         65 my $me = {};
446             # my $locale = setlocale(LC_ALL, "");
447 12         108 my $locale_values = localeconv();
448              
449             # Strip out illegal negative values from the current locale
450 12         41 foreach ( @IGNORE_NEGATIVE )
451             {
452 96 50 33     225 if (defined($locale_values->{$_}) && $locale_values->{$_} eq '-1')
453             {
454 0         0 delete $locale_values->{$_};
455             }
456             }
457              
458 12         98 while(my($arg, $default) = each %$DEFAULT_LOCALE)
459             {
460             $me->{$arg} = (( exists $locale_values->{$arg})
461             && $locale_values->{$arg} ne "")
462 324 100 66     836 ? $locale_values->{$arg}
463             : $default;
464              
465 324         646 foreach ($arg, uc $arg, "-$arg", uc "-$arg")
466             {
467 1256 100       2851 next unless defined $args{$_};
468 40         56 $me->{$arg} = $args{$_};
469 40         60 delete $args{$_};
470 40         112 last;
471             }
472             }
473              
474             #
475             # Some locales set the decimal_point to "," and the thousands_sep to "".
476             # This module generally defaults an empty thousands_sep to ",", creating a
477             # conflict in such a locale. Instead, leave the thousands_sep as the
478             # empty string. Suggested by Moritz Onken.
479 12         38 foreach my $prefix ("", "mon_")
480             {
481             $me->{"${prefix}thousands_sep"} = ""
482             if ($me->{"${prefix}decimal_point"} eq
483 24 50       94 $me->{"${prefix}thousands_sep"});
484             }
485              
486 12 50       48 croak "Invalid argument(s)" if %args;
487 12         32 bless $me, $type;
488 12         69 $me;
489             }
490              
491             ##----------------------------------------------------------------------
492              
493             =item round($number, $precision)
494              
495             Rounds the number to the specified precision. If C<$precision> is
496             omitted, the value of the C parameter is used (default
497             value 2). Both input and output are numeric (the function uses math
498             operators rather than string manipulation to do its job), The value of
499             C<$precision> may be any integer, positive or negative. Examples:
500              
501             round(3.14159) yields 3.14
502             round(3.14159, 4) yields 3.1416
503             round(42.00, 4) yields 42
504             round(1234, -2) yields 1200
505              
506             Since this is a mathematical rather than string oriented function,
507             there will be no trailing zeroes to the right of the decimal point,
508             and the C and C variables are ignored.
509             To format your number using the C and C
510             variables, use C instead.
511              
512             =cut
513              
514             sub round
515             {
516 121     121 1 4576 my ($self, $number, $precision) = _get_self @_;
517              
518 121 100       261 unless (defined($number))
519             {
520 1         5 _complain_undef();
521 1         7 $number = 0;
522             }
523              
524 121 100       236 $precision = $self->{decimal_digits} unless defined $precision;
525 121 50       249 $precision = 2 unless defined $precision;
526              
527 121 50       245 croak("precision must be integer")
528             unless int($precision) == $precision;
529              
530 121 50 33     260 if (ref($number) && $number->isa("Math::BigFloat"))
531             {
532 0         0 my $rounded = $number->copy();
533 0         0 $rounded->precision(-$precision);
534 0         0 return $rounded;
535             }
536              
537 121         214 my $sign = $number <=> 0;
538 121         226 my $multiplier = (10 ** $precision);
539 121         192 my $result = abs($number);
540 121         207 my $product = $result * $multiplier;
541              
542 121 100       416 croak "round() overflow. Try smaller precision or use Math::BigFloat"
543             if $product > MAX_INT;
544              
545             # We need to add 1e-14 to avoid some rounding errors due to the
546             # way floating point numbers work - see string-eq test in t/round.t
547 120         265 $result = int($product + .5 + 1e-14) / $multiplier;
548 120 100       213 $result = -$result if $sign < 0;
549 120         268 return $result;
550             }
551              
552             ##----------------------------------------------------------------------
553              
554             =item format_number($number, $precision, $trailing_zeroes)
555              
556             Formats a number by adding C between each set of 3
557             digits to the left of the decimal point, substituting C
558             for the decimal point, and rounding to the specified precision using
559             C. Note that C<$precision> is a I precision
560             specifier; trailing zeroes will only appear in the output if
561             C<$trailing_zeroes> is provided, or the parameter C is
562             set, with a value that is true (not zero, undef, or the empty string).
563             If C<$precision> is omitted, the value of the C
564             parameter (default value of 2) is used.
565              
566             If the value is too large or great to work with as a regular number,
567             but instead must be shown in scientific notation, returns that number
568             in scientific notation without further formatting.
569              
570             Examples:
571              
572             format_number(12345.6789) yields '12,345.68'
573             format_number(123456.789, 2) yields '123,456.79'
574             format_number(1234567.89, 2) yields '1,234,567.89'
575             format_number(1234567.8, 2) yields '1,234,567.8'
576             format_number(1234567.8, 2, 1) yields '1,234,567.80'
577             format_number(1.23456789, 6) yields '1.234568'
578             format_number("0.000020000E+00", 7);' yields '2e-05'
579              
580             Of course the output would have your values of C and
581             C instead of ',' and '.' respectively.
582              
583             =cut
584              
585             sub format_number
586             {
587 92     92 1 2011 my ($self, $number, $precision, $trailing_zeroes, $mon) = _get_self @_;
588              
589 92 100       208 unless (defined($number))
590             {
591 2         6 _complain_undef();
592 2         9 $number = 0;
593             }
594              
595 92         208 $self->_check_seps(); # first make sure the SEP variables are valid
596              
597             my($thousands_sep, $decimal_point) =
598             $mon ? @$self{qw(mon_thousands_sep mon_decimal_point)}
599 92 100       246 : @$self{qw(thousands_sep decimal_point)};
600              
601             # Set defaults and standardize number
602 92 100       190 $precision = $self->{decimal_digits} unless defined $precision;
603 92 100       218 $trailing_zeroes = $self->{decimal_fill} unless defined $trailing_zeroes;
604              
605             # Handle negative numbers
606 92         155 my $sign = $number <=> 0;
607 92 100       200 $number = abs($number) if $sign < 0;
608 92         194 $number = $self->round($number, $precision); # round off $number
609              
610             # detect scientific notation
611 91         179 my $exponent = 0;
612 91 50       538 if ($number =~ /^(-?[\d.]+)e([+-]\d+)$/)
613             {
614             # Don't attempt to format numbers that require scientific notation.
615 0         0 return $number;
616             }
617              
618             # Split integer and decimal parts of the number and add commas
619 91         181 my $integer = int($number);
620 91         110 my $decimal;
621              
622             # Note: In perl 5.6 and up, string representation of a number
623             # automagically includes the locale decimal point. This way we
624             # will detect the decimal part correctly as long as the decimal
625             # point is 1 character.
626 91 100       467 $decimal = substr($number, length($integer)+1)
627             if (length($integer) < length($number));
628 91 100       198 $decimal = '' unless defined $decimal;
629              
630             # Add trailing 0's if $trailing_zeroes is set.
631 91 100 100     308 $decimal .= '0'x( $precision - length($decimal) )
632             if $trailing_zeroes && $precision > length($decimal);
633              
634             # Add the commas (or whatever is in thousands_sep). If
635             # thousands_sep is the empty string, do nothing.
636 91 50       180 if ($thousands_sep)
637             {
638             # Add leading 0's so length($integer) is divisible by 3
639 91         263 $integer = '0'x(3 - (length($integer) % 3)).$integer;
640              
641             # Split $integer into groups of 3 characters and insert commas
642             $integer = join($thousands_sep,
643 91         472 grep {$_ ne ''} split(/(...)/, $integer));
  252         595  
644              
645             # Strip off leading zeroes and optional thousands separator
646 91         818 $integer =~ s/^0+(?:\Q$thousands_sep\E)?//;
647             }
648 91 100       242 $integer = '0' if $integer eq '';
649              
650             # Combine integer and decimal parts and return the result.
651 91 100 66     394 my $result = ((defined $decimal && length $decimal) ?
652             join($decimal_point, $integer, $decimal) :
653             $integer);
654              
655 91 100       387 return ($sign < 0) ? $self->format_negative($result) : $result;
656             }
657              
658             ##----------------------------------------------------------------------
659              
660             =item format_negative($number, $picture)
661              
662             Formats a negative number. Picture should be a string that contains
663             the letter C where the number should be inserted. For example, for
664             standard negative numbers you might use ``C<-x>'', while for
665             accounting purposes you might use ``C<(x)>''. If the specified number
666             begins with a ``-'' character, that will be removed before formatting,
667             but formatting will occur whether or not the number is negative.
668              
669             =cut
670              
671             sub format_negative
672             {
673 8     8 1 33 my($self, $number, $format) = _get_self @_;
674              
675 8 100       22 unless (defined($number))
676             {
677 1         4 _complain_undef();
678 1         48 $number = 0;
679             }
680              
681 8 50       20 $format = $self->{neg_format} unless defined $format;
682 8 50       28 croak "Letter x must be present in picture in format_negative()"
683             unless $format =~ /x/;
684 8         26 $number =~ s/^-//;
685 8         24 $format =~ s/x/$number/;
686 8         42 return $format;
687             }
688              
689             ##----------------------------------------------------------------------
690              
691             =item format_picture($number, $picture)
692              
693             Returns a string based on C<$picture> with the C<#> characters
694             replaced by digits from C<$number>. If the length of the integer part
695             of $number is too large to fit, the C<#> characters are replaced with
696             asterisks (C<*>) instead. Examples:
697              
698             format_picture(100.023, 'USD ##,###.##') yields 'USD 100.02'
699             format_picture(1000.23, 'USD ##,###.##') yields 'USD 1,000.23'
700             format_picture(10002.3, 'USD ##,###.##') yields 'USD 10,002.30'
701             format_picture(100023, 'USD ##,###.##') yields 'USD **,***.**'
702             format_picture(1.00023, 'USD #.###,###') yields 'USD 1.002,300'
703              
704             The comma (,) and period (.) you see in the picture examples should
705             match the values of C and C,
706             respectively, for proper operation. However, the C
707             characters in C<$picture> need not occur every three digits; the
708             I use of that variable by this function is to remove leading
709             commas (see the first example above). There may not be more than one
710             instance of C in C<$picture>.
711              
712             The value of C is used to determine how negative numbers
713             are displayed. The result of this is that the output of this function
714             my have unexpected spaces before and/or after the number. This is
715             necessary so that positive and negative numbers are formatted into a
716             space the same size. If you are only using positive numbers and want
717             to avoid this problem, set NEG_FORMAT to "x".
718              
719             =cut
720              
721             sub format_picture
722             {
723 13     13 1 48 my ($self, $number, $picture) = _get_self @_;
724              
725 13 100       29 unless (defined($number))
726             {
727 1         5 _complain_undef();
728 1         64 $number = 0;
729             }
730              
731 13 50       23 croak "Picture not defined" unless defined($picture);
732              
733 13         31 $self->_check_seps();
734              
735             # Handle negative numbers
736 13         61 my($neg_prefix) = $self->{neg_format} =~ /^([^x]+)/;
737 13         33 my($pic_prefix) = $picture =~ /^([^\#]+)/;
738 13         27 my $neg_pic = $self->{neg_format};
739 13         57 (my $pos_pic = $self->{neg_format}) =~ s/[^x\s]/ /g;
740 13         35 (my $pos_prefix = $neg_prefix) =~ s/[^x\s]/ /g;
741 13         40 $neg_pic =~ s/x/$picture/;
742 13         25 $pos_pic =~ s/x/$picture/;
743 13         26 my $sign = $number <=> 0;
744 13 100       30 $number = abs($number) if $sign < 0;
745 13 100       28 $picture = $sign < 0 ? $neg_pic : $pos_pic;
746 13 100       28 my $sign_prefix = $sign < 0 ? $neg_prefix : $pos_prefix;
747              
748             # Split up the picture and die if there is more than one $DECIMAL_POINT
749 13         76 my($pic_int, $pic_dec, @cruft) =
750             split(/\Q$self->{decimal_point}\E/, $picture);
751 13 50       28 $pic_int = '' unless defined $pic_int;
752 13 100       24 $pic_dec = '' unless defined $pic_dec;
753              
754 13 50       27 croak "Only one decimal separator permitted in picture"
755             if @cruft;
756              
757             # Obtain precision from the length of the decimal part...
758 13         16 my $precision = $pic_dec; # start with copying it
759 13         26 $precision =~ s/[^\#]//g; # eliminate all non-# characters
760 13         20 $precision = length $precision; # take the length of the result
761              
762             # Format the number
763 13         31 $number = $self->round($number, $precision);
764              
765             # Obtain the length of the integer portion just like we did for $precision
766 13         19 my $intsize = $pic_int; # start with copying it
767 13         65 $intsize =~ s/[^\#]//g; # eliminate all non-# characters
768 13         21 $intsize = length $intsize; # take the length of the result
769              
770             # Split up $number same as we did for $picture earlier
771 13         94 my($num_int, $num_dec) = split(/\./, $number, 2);
772 13 50       27 $num_int = '' unless defined $num_int;
773 13 100       33 $num_dec = '' unless defined $num_dec;
774              
775             # Check if the integer part will fit in the picture
776 13 100       35 if (length $num_int > $intsize)
777             {
778 2         10 $picture =~ s/\#/\*/g; # convert # to * and return it
779 2 50       7 $pic_prefix = "" unless defined $pic_prefix;
780 2         44 $picture =~ s/^(\Q$sign_prefix\E)(\Q$pic_prefix\E)(\s*)/$2$3$1/;
781 2         14 return $picture;
782             }
783              
784             # Split each portion of number and picture into arrays of characters
785 11         53 my @num_int = split(//, $num_int);
786 11         36 my @num_dec = split(//, $num_dec);
787 11         35 my @pic_int = split(//, $pic_int);
788 11         17 my @pic_dec = split(//, $pic_dec);
789              
790             # Now we copy those characters into @result.
791 11         14 my @result;
792             @result = ($self->{decimal_point})
793 11 100       59 if $picture =~ /\Q$self->{decimal_point}\E/;
794             # For each characture in the decimal part of the picture, replace '#'
795             # signs with digits from the number.
796 11         21 my $char;
797 11         23 foreach $char (@pic_dec)
798             {
799 18 100 100     54 $char = (shift(@num_dec) || 0) if ($char eq '#');
800 18         42 push (@result, $char);
801             }
802              
803             # For each character in the integer part of the picture (moving right
804             # to left this time), replace '#' signs with digits from the number,
805             # or spaces if we've run out of numbers.
806 11         34 while ($char = pop @pic_int)
807             {
808 121 100       204 $char = pop(@num_int) if ($char eq '#');
809             $char = ' ' if (!defined($char) ||
810 121 100 100     318 $char eq $self->{thousands_sep} && $#num_int < 0);
      100        
811 121         240 unshift (@result, $char);
812             }
813              
814             # Combine @result into a string and return it.
815 11         30 my $result = join('', @result);
816 11 50       22 $sign_prefix = '' unless defined $sign_prefix;
817 11 100       20 $pic_prefix = '' unless defined $pic_prefix;
818 11         190 $result =~ s/^(\Q$sign_prefix\E)(\Q$pic_prefix\E)(\s*)/$2$3$1/;
819 11         115 $result;
820             }
821              
822             ##----------------------------------------------------------------------
823              
824             =item format_price($number, $precision, $symbol)
825              
826             Returns a string containing C<$number> formatted similarly to
827             C, except that the decimal portion may have trailing
828             zeroes added to make it be exactly C<$precision> characters long, and
829             the currency string will be prefixed.
830              
831             The C<$symbol> attribute may be one of "INT_CURR_SYMBOL" or
832             "CURRENCY_SYMBOL" (case insensitive) to use the value of that
833             attribute of the object, or a string containing the symbol to be used.
834             The default is "INT_CURR_SYMBOL" if this argument is undefined or not
835             given; if set to the empty string, or if set to undef and the
836             C attribute of the object is the empty string, no
837             currency will be added.
838              
839             If C<$precision> is not provided, the default of 2 will be used.
840             Examples:
841              
842             format_price(12.95) yields 'USD 12.95'
843             format_price(12) yields 'USD 12.00'
844             format_price(12, 3) yields '12.000'
845              
846             The third example assumes that C is the empty string.
847              
848             =cut
849              
850             sub format_price
851             {
852 55     55 1 17426 my ($self, $number, $precision, $curr_symbol) = _get_self @_;
853              
854 55 100       120 unless (defined($number))
855             {
856 1         4 _complain_undef();
857 1         45 $number = 0;
858             }
859              
860             # Determine what the monetary symbol should be
861             $curr_symbol = $self->{int_curr_symbol}
862 55 100 66     168 if (!defined($curr_symbol) || lc($curr_symbol) eq "int_curr_symbol");
863             $curr_symbol = $self->{currency_symbol}
864 55 100 66     216 if (!defined($curr_symbol) || lc($curr_symbol) eq "currency_symbol");
865 55 50       105 $curr_symbol = "" unless defined($curr_symbol);
866              
867             # Determine which value to use for frac digits
868             my $frac_digits = ($curr_symbol eq $self->{int_curr_symbol} ?
869 55 100       141 $self->{int_frac_digits} : $self->{frac_digits});
870              
871             # Determine precision for decimal portion
872 55 100       124 $precision = $frac_digits unless defined $precision;
873 55 50       92 $precision = $self->{decimal_digits} unless defined $precision; # fallback
874 55 50       86 $precision = 2 unless defined $precision; # default
875              
876             # Determine sign and absolute value
877 55         114 my $sign = $number <=> 0;
878 55 100       118 $number = abs($number) if $sign < 0;
879              
880             # format it first
881 55         124 $number = $self->format_number($number, $precision, undef, 1);
882              
883             # Now we make sure the decimal part has enough zeroes
884 55         232 my ($integer, $decimal) =
885             split(/\Q$self->{mon_decimal_point}\E/, $number, 2);
886 55 100       125 $decimal = '0'x$precision unless $decimal;
887 55         98 $decimal .= '0'x($precision - length $decimal);
888              
889             # Extract positive or negative values
890 55         80 my($sep_by_space, $cs_precedes, $sign_posn, $sign_symbol);
891 55 100       93 if ($sign < 0)
892             {
893 41         65 $sep_by_space = $self->{n_sep_by_space};
894 41         60 $cs_precedes = $self->{n_cs_precedes};
895 41         58 $sign_posn = $self->{n_sign_posn};
896 41         65 $sign_symbol = $self->{negative_sign};
897             }
898             else
899             {
900 14         26 $sep_by_space = $self->{p_sep_by_space};
901 14         17 $cs_precedes = $self->{p_cs_precedes};
902 14         18 $sign_posn = $self->{p_sign_posn};
903 14         25 $sign_symbol = $self->{positive_sign};
904             }
905              
906             # Combine it all back together.
907             my $result = ($precision ?
908 55 100       119 join($self->{mon_decimal_point}, $integer, $decimal) :
909             $integer);
910              
911             # Determine where spaces go, if any
912 55         76 my($sign_sep, $curr_sep);
913 55 100       123 if ($sep_by_space == 0)
    100          
    50          
914             {
915 20         30 $sign_sep = $curr_sep = "";
916             }
917             elsif ($sep_by_space == 1)
918             {
919 23         33 $sign_sep = "";
920 23         33 $curr_sep = " ";
921             }
922             elsif ($sep_by_space == 2)
923             {
924 12         19 $sign_sep = " ";
925 12         15 $curr_sep = "";
926             }
927             else
928             {
929 0         0 croak "Invalid sep_by_space value";
930             }
931              
932             # Add sign, if any
933 55 100 66     215 if ($sign_posn >= 0 && $sign_posn <= 2)
    50 66        
934             {
935             # Combine with currency symbol and return
936 35 50       64 if ($curr_symbol ne "")
937             {
938 35 100       59 if ($cs_precedes)
939             {
940 26         48 $result = $curr_symbol.$curr_sep.$result;
941             }
942             else
943             {
944 9         16 $result = $result.$curr_sep.$curr_symbol;
945             }
946             }
947              
948 35 100       91 if ($sign_posn == 0)
    100          
949             {
950 7         38 return "($result)";
951             }
952             elsif ($sign_posn == 1)
953             {
954 21         135 return $sign_symbol.$sign_sep.$result;
955             }
956             else # $sign_posn == 2
957             {
958 7         35 return $result.$sign_sep.$sign_symbol;
959             }
960             }
961              
962             elsif ($sign_posn == 3 || $sign_posn == 4)
963             {
964 20 100       34 if ($sign_posn == 3)
965             {
966 13         22 $curr_symbol = $sign_symbol.$sign_sep.$curr_symbol;
967             }
968             else # $sign_posn == 4
969             {
970 7         17 $curr_symbol = $curr_symbol.$sign_sep.$sign_symbol;
971             }
972              
973             # Combine with currency symbol and return
974 20 100       38 if ($cs_precedes)
975             {
976 11         56 return $curr_symbol.$curr_sep.$result;
977             }
978             else
979             {
980 9         47 return $result.$curr_sep.$curr_symbol;
981             }
982             }
983              
984             else
985             {
986 0         0 croak "Invalid *_sign_posn value";
987             }
988             }
989              
990             ##----------------------------------------------------------------------
991              
992             =item format_bytes($number, %options)
993              
994             =item format_bytes($number, $precision) # deprecated
995              
996             Returns a string containing C<$number> formatted similarly to
997             C, except that large numbers may be abbreviated by
998             adding a suffix to indicate 1024, 1,048,576, or 1,073,741,824 bytes.
999             Suffix may be the traditional K, M, or G (default); or the IEC
1000             standard 60027 "KiB," "MiB," or "GiB" depending on the "mode" option.
1001              
1002             Negative values will result in an error.
1003              
1004             The second parameter can be either a hash that sets options, or a
1005             number. Using a number here is deprecated and will generate a
1006             warning; early versions of Number::Format only allowed a numeric
1007             value. A future release of Number::Format will change this warning to
1008             an error. New code should use a hash instead to set options. If it
1009             is a number this sets the value of the "precision" option.
1010              
1011             Valid options are:
1012              
1013             =over 4
1014              
1015             =item precision
1016              
1017             Set the precision for displaying numbers. If not provided, a default
1018             of 2 will be used. Examples:
1019              
1020             format_bytes(12.95) yields '12.95'
1021             format_bytes(12.95, precision => 0) yields '13'
1022             format_bytes(2048) yields '2K'
1023             format_bytes(2048, mode => "iec") yields '2KiB'
1024             format_bytes(9999999) yields '9.54M'
1025             format_bytes(9999999, precision => 1) yields '9.5M'
1026              
1027             =item unit
1028              
1029             Sets the default units used for the results. The default is to
1030             determine this automatically in order to minimize the length of the
1031             string. In other words, numbers greater than or equal to 1024 (or
1032             other number given by the 'base' option, q.v.) will be divided by 1024
1033             and C<$KILO_SUFFIX> or C<$KIBI_SUFFIX> added; if greater than or equal
1034             to 1048576 (1024*1024), it will be divided by 1048576 and
1035             C<$MEGA_SUFFIX> or C<$MEBI_SUFFIX> appended to the end; etc.
1036              
1037             However if a value is given for C it will use that value
1038             instead. The first letter (case-insensitive) of the value given
1039             indicates the threshhold for conversion; acceptable values are G (for
1040             giga/gibi), M (for mega/mebi), K (for kilo/kibi), or A (for automatic,
1041             the default). For example:
1042              
1043             format_bytes(1048576, unit => 'K') yields '1,024K'
1044             instead of '1M'
1045              
1046             Note that the valid values to this option do not vary even when the
1047             suffix configuration variables have been changed.
1048              
1049             =item base
1050              
1051             Sets the number at which the C<$KILO_SUFFIX> is added. Default is
1052             1024. Set to any value; the only other useful value is probably 1000,
1053             as hard disk manufacturers use that number to make their disks sound
1054             bigger than they really are.
1055              
1056             If the mode (see below) is set to "iec" or "iec60027" then setting the
1057             base option results in an error.
1058              
1059             =item mode
1060              
1061             Traditionally, bytes have been given in SI (metric) units such as
1062             "kilo" and "mega" even though they represent powers of 2 (1024, etc.)
1063             rather than powers of 10 (1000, etc.) This "binary prefix" causes
1064             much confusion in consumer products where "GB" may mean either
1065             1,048,576 or 1,000,000, for example. The International
1066             Electrotechnical Commission has created standard IEC 60027 to
1067             introduce prefixes Ki, Mi, Gi, etc. ("kibibytes," "mebibytes,"
1068             "gibibytes," etc.) to remove this confusion. Specify a mode option
1069             with either "traditional" or "iec60027" (or abbreviate as "trad" or
1070             "iec") to indicate which type of binary prefix you want format_bytes
1071             to use. For backward compatibility, "traditional" is the default.
1072             See http://en.wikipedia.org/wiki/Binary_prefix for more information.
1073              
1074             =back
1075              
1076             =cut
1077              
1078             sub format_bytes
1079             {
1080 18     18 1 146 my ($self, $number, @options) = _get_self @_;
1081              
1082 18 100       41 unless (defined($number))
1083             {
1084 1         3 _complain_undef();
1085 1         8 $number = 0;
1086             }
1087              
1088 18 50       42 croak "Negative number not allowed in format_bytes"
1089             if $number < 0;
1090              
1091             # If a single scalar is given instead of key/value pairs for
1092             # @options, treat that as the value of the precision option.
1093 18         27 my %options;
1094 18 50       37 if (@options == 1)
1095             {
1096             # To be changed to 'croak' in a future release:
1097 0         0 carp "format_bytes: number instead of options is deprecated";
1098 0         0 %options = ( precision => $options[0] );
1099             }
1100             else
1101             {
1102 18         40 %options = @options;
1103             }
1104              
1105             # Set default for precision. Test using defined because it may be 0.
1106             $options{precision} = $self->{decimal_digits}
1107 18 100       50 unless defined $options{precision};
1108             $options{precision} = 2
1109 18 50       45 unless defined $options{precision}; # default
1110              
1111 18   100     67 $options{mode} ||= "traditional";
1112 18         27 my($ksuff, $msuff, $gsuff);
1113 18 100       108 if ($options{mode} =~ /^iec(60027)?$/i)
    50          
1114             {
1115             ($ksuff, $msuff, $gsuff) =
1116 6         30 @$self{qw(kibi_suffix mebi_suffix gibi_suffix)};
1117             croak "base option not allowed in iec60027 mode"
1118 6 50       21 if exists $options{base};
1119             }
1120             elsif ($options{mode} =~ /^trad(itional)?$/i)
1121             {
1122             ($ksuff, $msuff, $gsuff) =
1123 12         37 @$self{qw(kilo_suffix mega_suffix giga_suffix)};
1124             }
1125             else
1126             {
1127 0         0 croak "Invalid mode";
1128             }
1129              
1130             # Set default for "base" option. Calculate threshold values for
1131             # kilo, mega, and giga values. On 32-bit systems tera would cause
1132             # overflows so it is not supported. Useful values of "base" are
1133             # 1024 or 1000, but any number can be used. Larger numbers may
1134             # cause overflows for giga or even mega, however.
1135 18         49 my %mult = _get_multipliers($options{base});
1136              
1137             # Process "unit" option. Set default, then take first character
1138             # and convert to upper case.
1139             $options{unit} = "auto"
1140 18 100       57 unless defined $options{unit};
1141 18         48 my $unit = uc(substr($options{unit},0,1));
1142              
1143             # Process "auto" first (default). Based on size of number,
1144             # automatically determine which unit to use.
1145 18 100       38 if ($unit eq 'A')
1146             {
1147 16 100       46 if ($number >= $mult{giga})
    100          
    100          
1148             {
1149 2         4 $unit = 'G';
1150             }
1151             elsif ($number >= $mult{mega})
1152             {
1153 6         9 $unit = 'M';
1154             }
1155             elsif ($number >= $mult{kilo})
1156             {
1157 3         5 $unit = 'K';
1158             }
1159             else
1160             {
1161 5         9 $unit = 'N';
1162             }
1163             }
1164              
1165             # Based on unit, whether specified or determined above, divide the
1166             # number and determine what suffix to use.
1167 18         80 my $suffix = "";
1168 18 100       52 if ($unit eq 'G')
    100          
    100          
    50          
1169             {
1170 2         3 $number /= $mult{giga};
1171 2         4 $suffix = $gsuff;
1172             }
1173             elsif ($unit eq 'M')
1174             {
1175 6         12 $number /= $mult{mega};
1176 6         9 $suffix = $msuff;
1177             }
1178             elsif ($unit eq 'K')
1179             {
1180 5         9 $number /= $mult{kilo};
1181 5         8 $suffix = $ksuff;
1182             }
1183             elsif ($unit ne 'N')
1184             {
1185 0         0 croak "Invalid unit option";
1186             }
1187              
1188             # Format the number and add the suffix.
1189 18         48 return $self->format_number($number, $options{precision}) . $suffix;
1190             }
1191              
1192             ##----------------------------------------------------------------------
1193              
1194             =item unformat_number($formatted)
1195              
1196             Converts a string as returned by C,
1197             C, or C, and returns the
1198             corresponding value as a numeric scalar. Returns C if the
1199             number does not contain any digits. Examples:
1200              
1201             unformat_number('USD 12.95') yields 12.95
1202             unformat_number('USD 12.00') yields 12
1203             unformat_number('foobar') yields undef
1204             unformat_number('1234-567@.8') yields 1234567.8
1205              
1206             The value of C is used to determine where to separate
1207             the integer and decimal portions of the input. All other non-digit
1208             characters, including but not limited to C and
1209             C, are removed.
1210              
1211             If the number matches the pattern of C I there is a
1212             ``-'' character before any of the digits, then a negative number is
1213             returned.
1214              
1215             If the number ends with the C, C,
1216             C, C, C, or C
1217             characters, then the number returned will be multiplied by the
1218             appropriate multiple of 1024 (or if the base option is given, by the
1219             multiple of that value) as appropriate. Examples:
1220              
1221             unformat_number("4K", base => 1024) yields 4096
1222             unformat_number("4K", base => 1000) yields 4000
1223             unformat_number("4KiB", base => 1024) yields 4096
1224             unformat_number("4G") yields 4294967296
1225              
1226             =cut
1227              
1228             sub unformat_number
1229             {
1230 20     20 1 2476 my ($self, $formatted, %options) = _get_self @_;
1231              
1232 20 100       52 unless (defined($formatted))
1233             {
1234 1         3 _complain_undef();
1235 1         8 $formatted = "";
1236             }
1237              
1238 20         53 $self->_check_seps();
1239 20 100       73 return undef unless $formatted =~ /\d/; # require at least one digit
1240              
1241             # Regular expression for detecting decimal point
1242 18         127 my $pt = qr/\Q$self->{decimal_point}\E/;
1243              
1244             # ru_RU locale has comma for decimal_point, but period for
1245             # mon_decimal_point! But as long as thousands_sep is different
1246             # from either, we can allow either decimal point.
1247 18 0 33     116 if ($self->{mon_decimal_point} &&
      33        
      33        
1248             $self->{decimal_point} ne $self->{mon_decimal_point} &&
1249             $self->{decimal_point} ne $self->{mon_thousands_sep} &&
1250             $self->{mon_decimal_point} ne $self->{thousands_sep})
1251             {
1252 0         0 $pt = qr/(?:\Q$self->{decimal_point}\E|
1253             \Q$self->{mon_decimal_point}\E)/x;
1254             }
1255              
1256             # Detect if it ends with one of the kilo / mega / giga suffixes.
1257 18         180 my $kp = ($formatted =~
1258             s/\s*($self->{kilo_suffix}|$self->{kibi_suffix})\s*$//);
1259 18         113 my $mp = ($formatted =~
1260             s/\s*($self->{mega_suffix}|$self->{mebi_suffix})\s*$//);
1261 18         111 my $gp = ($formatted =~
1262             s/\s*($self->{giga_suffix}|$self->{gibi_suffix})\s*$//);
1263 18         51 my %mult = _get_multipliers($options{base});
1264              
1265             # Split number into integer and decimal parts
1266 14         99 my ($integer, $decimal, @cruft) = split($pt, $formatted);
1267 14 50       46 croak "Only one decimal separator permitted"
1268             if @cruft;
1269              
1270             # It's negative if the first non-digit character is a -
1271 14 100       40 my $sign = $formatted =~ /^\D*-/ ? -1 : 1;
1272 14         47 my($before_re, $after_re) = split /x/, $self->{neg_format}, 2;
1273 14 100       130 $sign = -1 if $formatted =~ /\Q$before_re\E(.+)\Q$after_re\E/;
1274              
1275             # Strip out all non-digits from integer and decimal parts
1276 14 50       35 $integer = '' unless defined $integer;
1277 14 100       29 $decimal = '' unless defined $decimal;
1278 14         48 $integer =~ s/\D//g;
1279 14         25 $decimal =~ s/\D//g;
1280              
1281             # Join back up, using period, and add 0 to make Perl think it's a number
1282 14         57 my $number = join('.', $integer, $decimal) + 0;
1283 14 100       37 $number = -$number if $sign < 0;
1284              
1285             # Scale the number if it ended in kilo or mega suffix.
1286 14 100       36 $number *= $mult{kilo} if $kp;
1287 14 100       26 $number *= $mult{mega} if $mp;
1288 14 100       24 $number *= $mult{giga} if $gp;
1289              
1290 14         108 return $number;
1291             }
1292              
1293             ###---------------------------------------------------------------------
1294              
1295             =back
1296              
1297             =head1 CAVEATS
1298              
1299             Some systems, notably OpenBSD, may have incomplete locale support.
1300             Using this module together with L in OpenBSD may therefore
1301             not produce the intended results.
1302              
1303             =head1 BUGS
1304              
1305             No known bugs at this time. Report bugs using the CPAN request
1306             tracker at L
1307             or by email to the author.
1308              
1309             =head1 AUTHOR
1310              
1311             William R. Ward, SwPrAwM@cpan.org (remove "SPAM" before sending email,
1312             leaving only my initials)
1313              
1314             =head1 SEE ALSO
1315              
1316             perl(1).
1317              
1318             =cut
1319              
1320             1;