1Format(3) User Contributed Perl Documentation Format(3)
2
3
4
6 Number::Format - Perl extension for formatting numbers
7
9 use Number::Format;
10 my $x = new Number::Format %args;
11 $formatted = $x->round($number, $precision);
12 $formatted = $x->format_number($number, $precision, $trailing_zeroes);
13 $formatted = $x->format_negative($number, $picture);
14 $formatted = $x->format_picture($number, $picture);
15 $formatted = $x->format_price($number, $precision, $symbol);
16 $formatted = $x->format_bytes($number, $precision);
17 $number = $x->unformat_number($formatted);
18
19 use Number::Format qw(:subs);
20 $formatted = round($number, $precision);
21 $formatted = format_number($number, $precision, $trailing_zeroes);
22 $formatted = format_negative($number, $picture);
23 $formatted = format_picture($number, $picture);
24 $formatted = format_price($number, $precision, $symbol);
25 $formatted = format_bytes($number, $precision);
26 $number = unformat_number($formatted);
27
29 Perl, version 5.8 or higher.
30
31 POSIX.pm to determine locale settings.
32
33 Carp.pm is used for some error reporting.
34
36 These functions provide an easy means of formatting numbers in a manner
37 suitable for displaying to the user.
38
39 There are two ways to use this package. One is to declare an object of
40 type Number::Format, which you can think of as a formatting engine.
41 The various functions defined here are provided as object methods. The
42 constructor new() can be used to set the parameters of the formatting
43 engine. Valid parameters are:
44
45 THOUSANDS_SEP - character inserted between groups of 3 digits
46 DECIMAL_POINT - character separating integer and fractional parts
47 MON_THOUSANDS_SEP - like THOUSANDS_SEP, but used for format_price
48 MON_DECIMAL_POINT - like DECIMAL_POINT, but used for format_price
49 INT_CURR_SYMBOL - character(s) denoting currency (see format_price())
50 DECIMAL_DIGITS - number of digits to the right of dec point (def 2)
51 DECIMAL_FILL - boolean; whether to add zeroes to fill out decimal
52 NEG_FORMAT - format to display negative numbers (def ``-x'')
53 KILO_SUFFIX - suffix to add when format_bytes formats kilobytes (trad)
54 MEGA_SUFFIX - " " " " " " megabytes (trad)
55 GIGA_SUFFIX - " " " " " " gigabytes (trad)
56 KIBI_SUFFIX - suffix to add when format_bytes formats kibibytes (iec)
57 MEBI_SUFFIX - " " " " " " mebibytes (iec)
58 GIBI_SUFFIX - " " " " " " gibibytes (iec)
59
60 They may be specified in upper or lower case, with or without a leading
61 hyphen ( - ).
62
63 If "THOUSANDS_SEP" is set to the empty string, format_number will not
64 insert any separators.
65
66 The defaults for "THOUSANDS_SEP", "DECIMAL_POINT", "MON_THOUSANDS_SEP",
67 "MON_DECIMAL_POINT", and "INT_CURR_SYMBOL" come from the POSIX locale
68 information (see perllocale). If your POSIX locale does not provide
69 "MON_THOUSANDS_SEP" and/or "MON_DECIMAL_POINT" fields, then the
70 "THOUSANDS_SEP" and/or "DECIMAL_POINT" values are used for those
71 parameters. Formerly, POSIX was optional but this caused problems in
72 some cases, so it is now required. If this causes you hardship, please
73 contact the author of this package at <SwPrAwM@cpan.org> (remove "SPAM"
74 to get correct email address) for help.
75
76 If any of the above parameters are not specified when you invoke new(),
77 then the values are taken from package global variables of the same
78 name (e.g. $DECIMAL_POINT is the default for the "DECIMAL_POINT"
79 parameter). If you use the ":vars" keyword on your "use
80 Number::Format" line (see non-object-oriented example below) you will
81 import those variables into your namesapce and can assign values as if
82 they were your own local variables. The default values for all the
83 parameters are:
84
85 THOUSANDS_SEP = ','
86 DECIMAL_POINT = '.'
87 MON_THOUSANDS_SEP = ','
88 MON_DECIMAL_POINT = '.'
89 INT_CURR_SYMBOL = 'USD'
90 DECIMAL_DIGITS = 2
91 DECIMAL_FILL = 0
92 NEG_FORMAT = '-x'
93 KILO_SUFFIX = 'K'
94 MEGA_SUFFIX = 'M'
95 GIGA_SUFFIX = 'G'
96 KIBI_SUFFIX = 'KiB'
97 MEBI_SUFFIX = 'MiB'
98 GIBI_SUFFIX = 'GiB'
99
100 Note however that when you first call one of the functions in this
101 module without using the object-oriented interface, further setting of
102 those global variables will have no effect on non-OO calls. It is
103 recommended that you use the object-oriented interface instead for
104 fewer headaches and a cleaner design.
105
106 The "DECIMAL_FILL" and "DECIMAL_DIGITS" values are not set by the
107 Locale system, but are definable by the user. They affect the output
108 of format_number(). Setting "DECIMAL_DIGITS" is like giving that value
109 as the $precision argument to that function. Setting "DECIMAL_FILL" to
110 a true value causes format_number() to append zeroes to the right of
111 the decimal digits until the length is the specified number of digits.
112
113 "NEG_FORMAT" is only used by format_negative() and is a string
114 containing the letter 'x', where that letter will be replaced by a
115 positive representation of the number being passed to that function.
116 format_number() and format_price() utilize this feature by calling
117 format_negative() if the number was less than 0.
118
119 "KILO_SUFFIX", "MEGA_SUFFIX", and "GIGA_SUFFIX" are used by
120 format_bytes() when the value is over 1024, 1024*1024, or
121 1024*1024*1024, respectively. The default values are "K", "M", and
122 "G". These apply in the default "traditional" mode only. Note: TERA
123 or higher are not implemented because of integer overflows on 32-bit
124 systems.
125
126 "KIBI_SUFFIX", "MEBI_SUFFIX", and "GIBI_SUFFIX" are used by
127 format_bytes() when the value is over 1024, 1024*1024, or
128 1024*1024*1024, respectively. The default values are "KiB", "MiB", and
129 "GiB". These apply in the "iso60027"" mode only. Note: TEBI or higher
130 are not implemented because of integer overflows on 32-bit systems.
131
132 The only restrictions on "DECIMAL_POINT" and "THOUSANDS_SEP" are that
133 they must not be digits and must not be identical. There are no
134 restrictions on "INT_CURR_SYMBOL".
135
136 For example, a German user might include this in their code:
137
138 use Number::Format;
139 my $de = new Number::Format(-thousands_sep => '.',
140 -decimal_point => ',',
141 -int_curr_symbol => 'DEM');
142 my $formatted = $de->format_number($number);
143
144 Or, if you prefer not to use the object oriented interface, you can do
145 this instead:
146
147 use Number::Format qw(:subs :vars);
148 $THOUSANDS_SEP = '.';
149 $DECIMAL_POINT = ',';
150 $INT_CURR_SYMBOL = 'DEM';
151 my $formatted = format_number($number);
152
154 Nothing is exported by default. To export the functions or the global
155 variables defined herein, specify the function name(s) on the import
156 list of the "use Number::Format" statement. To export all functions
157 defined herein, use the special tag ":subs". To export the variables,
158 use the special tag ":vars"; to export both subs and vars you can use
159 the tag ":all".
160
162 new( %args )
163 Creates a new Number::Format object. Valid keys for %args are any
164 of the parameters described above. Keys may be in all uppercase or
165 all lowercase, and may optionally be preceded by a hyphen (-)
166 character. Example:
167
168 my $de = new Number::Format(-thousands_sep => '.',
169 -decimal_point => ',',
170 -int_curr_symbol => 'DEM');
171
172 round($number, $precision)
173 Rounds the number to the specified precision. If $precision is
174 omitted, the value of the "DECIMAL_DIGITS" parameter is used
175 (default value 2). Both input and output are numeric (the function
176 uses math operators rather than string manipulation to do its job),
177 The value of $precision may be any integer, positive or negative.
178 Examples:
179
180 round(3.14159) yields 3.14
181 round(3.14159, 4) yields 3.1416
182 round(42.00, 4) yields 42
183 round(1234, -2) yields 1200
184
185 Since this is a mathematical rather than string oriented function,
186 there will be no trailing zeroes to the right of the decimal point,
187 and the "DECIMAL_POINT" and "THOUSANDS_SEP" variables are ignored.
188 To format your number using the "DECIMAL_POINT" and "THOUSANDS_SEP"
189 variables, use format_number() instead.
190
191 format_number($number, $precision, $trailing_zeroes)
192 Formats a number by adding "THOUSANDS_SEP" between each set of 3
193 digits to the left of the decimal point, substituting
194 "DECIMAL_POINT" for the decimal point, and rounding to the
195 specified precision using round(). Note that $precision is a
196 maximum precision specifier; trailing zeroes will only appear in
197 the output if $trailing_zeroes is provided, or the parameter
198 "DECIMAL_FILL" is set, with a value that is true (not zero, undef,
199 or the empty string). If $precision is omitted, the value of the
200 "DECIMAL_DIGITS" parameter (default value of 2) is used.
201
202 If the value is too large or great to work with as a regular
203 number, but instead must be shown in scientific notation, returns
204 that number in scientific notation without further formatting.
205
206 Examples:
207
208 format_number(12345.6789) yields '12,345.68'
209 format_number(123456.789, 2) yields '123,456.79'
210 format_number(1234567.89, 2) yields '1,234,567.89'
211 format_number(1234567.8, 2) yields '1,234,567.8'
212 format_number(1234567.8, 2, 1) yields '1,234,567.80'
213 format_number(1.23456789, 6) yields '1.234568'
214 format_number("0.000020000E+00", 7);' yields '2e-05'
215
216 Of course the output would have your values of "THOUSANDS_SEP" and
217 "DECIMAL_POINT" instead of ',' and '.' respectively.
218
219 format_negative($number, $picture)
220 Formats a negative number. Picture should be a string that
221 contains the letter "x" where the number should be inserted. For
222 example, for standard negative numbers you might use ``"-x"'',
223 while for accounting purposes you might use ``"(x)"''. If the
224 specified number begins with a ``-'' character, that will be
225 removed before formatting, but formatting will occur whether or not
226 the number is negative.
227
228 format_picture($number, $picture)
229 Returns a string based on $picture with the "#" characters replaced
230 by digits from $number. If the length of the integer part of
231 $number is too large to fit, the "#" characters are replaced with
232 asterisks ("*") instead. Examples:
233
234 format_picture(100.023, 'USD ##,###.##') yields 'USD 100.02'
235 format_picture(1000.23, 'USD ##,###.##') yields 'USD 1,000.23'
236 format_picture(10002.3, 'USD ##,###.##') yields 'USD 10,002.30'
237 format_picture(100023, 'USD ##,###.##') yields 'USD **,***.**'
238 format_picture(1.00023, 'USD #.###,###') yields 'USD 1.002,300'
239
240 The comma (,) and period (.) you see in the picture examples should
241 match the values of "THOUSANDS_SEP" and "DECIMAL_POINT",
242 respectively, for proper operation. However, the "THOUSANDS_SEP"
243 characters in $picture need not occur every three digits; the only
244 use of that variable by this function is to remove leading commas
245 (see the first example above). There may not be more than one
246 instance of "DECIMAL_POINT" in $picture.
247
248 The value of "NEG_FORMAT" is used to determine how negative numbers
249 are displayed. The result of this is that the output of this
250 function my have unexpected spaces before and/or after the number.
251 This is necessary so that positive and negative numbers are
252 formatted into a space the same size. If you are only using
253 positive numbers and want to avoid this problem, set NEG_FORMAT to
254 "x".
255
256 format_price($number, $precision, $symbol)
257 Returns a string containing $number formatted similarly to
258 format_number(), except that the decimal portion may have trailing
259 zeroes added to make it be exactly $precision characters long, and
260 the currency string will be prefixed.
261
262 The $symbol attribute may be one of "INT_CURR_SYMBOL" or
263 "CURRENCY_SYMBOL" (case insensitive) to use the value of that
264 attribute of the object, or a string containing the symbol to be
265 used. The default is "INT_CURR_SYMBOL" if this argument is
266 undefined or not given; if set to the empty string, or if set to
267 undef and the "INT_CURR_SYMBOL" attribute of the object is the
268 empty string, no currency will be added.
269
270 If $precision is not provided, the default of 2 will be used.
271 Examples:
272
273 format_price(12.95) yields 'USD 12.95'
274 format_price(12) yields 'USD 12.00'
275 format_price(12, 3) yields '12.000'
276
277 The third example assumes that "INT_CURR_SYMBOL" is the empty
278 string.
279
280 format_bytes($number, %options)
281 format_bytes($number, $precision) # deprecated
282 Returns a string containing $number formatted similarly to
283 format_number(), except that large numbers may be abbreviated by
284 adding a suffix to indicate 1024, 1,048,576, or 1,073,741,824
285 bytes. Suffix may be the traditional K, M, or G (default); or the
286 IEC standard 60027 "KiB," "MiB," or "GiB" depending on the "mode"
287 option.
288
289 Negative values will result in an error.
290
291 The second parameter can be either a hash that sets options, or a
292 number. Using a number here is deprecated and will generate a
293 warning; early versions of Number::Format only allowed a numeric
294 value. A future release of Number::Format will change this warning
295 to an error. New code should use a hash instead to set options.
296 If it is a number this sets the value of the "precision" option.
297
298 Valid options are:
299
300 precision
301 Set the precision for displaying numbers. If not provided, a
302 default of 2 will be used. Examples:
303
304 format_bytes(12.95) yields '12.95'
305 format_bytes(12.95, precision => 0) yields '13'
306 format_bytes(2048) yields '2K'
307 format_bytes(2048, mode => "iec") yields '2KiB'
308 format_bytes(9999999) yields '9.54M'
309 format_bytes(9999999, precision => 1) yields '9.5M'
310
311 unit
312 Sets the default units used for the results. The default is to
313 determine this automatically in order to minimize the length of
314 the string. In other words, numbers greater than or equal to
315 1024 (or other number given by the 'base' option, q.v.) will be
316 divided by 1024 and $KILO_SUFFIX or $KIBI_SUFFIX added; if
317 greater than or equal to 1048576 (1024*1024), it will be
318 divided by 1048576 and $MEGA_SUFFIX or $MEBI_SUFFIX appended to
319 the end; etc.
320
321 However if a value is given for "unit" it will use that value
322 instead. The first letter (case-insensitive) of the value
323 given indicates the threshhold for conversion; acceptable
324 values are G (for giga/gibi), M (for mega/mebi), K (for
325 kilo/kibi), or A (for automatic, the default). For example:
326
327 format_bytes(1048576, unit => 'K') yields '1,024K'
328 instead of '1M'
329
330 Note that the valid values to this option do not vary even when
331 the suffix configuration variables have been changed.
332
333 base
334 Sets the number at which the $KILO_SUFFIX is added. Default is
335 1024. Set to any value; the only other useful value is
336 probably 1000, as hard disk manufacturers use that number to
337 make their disks sound bigger than they really are.
338
339 If the mode (see below) is set to "iec" or "iec60027" then
340 setting the base option results in an error.
341
342 mode
343 Traditionally, bytes have been given in SI (metric) units such
344 as "kilo" and "mega" even though they represent powers of 2
345 (1024, etc.) rather than powers of 10 (1000, etc.) This
346 "binary prefix" causes much confusion in consumer products
347 where "GB" may mean either 1,048,576 or 1,000,000, for example.
348 The International Electrotechnical Commission has created
349 standard IEC 60027 to introduce prefixes Ki, Mi, Gi, etc.
350 ("kibibytes," "mebibytes," "gibibytes," etc.) to remove this
351 confusion. Specify a mode option with either "traditional" or
352 "iec60027" (or abbreviate as "trad" or "iec") to indicate which
353 type of binary prefix you want format_bytes to use. For
354 backward compatibility, "traditional" is the default. See
355 http://en.wikipedia.org/wiki/Binary_prefix for more
356 information.
357
358 unformat_number($formatted)
359 Converts a string as returned by format_number(), format_price(),
360 or format_picture(), and returns the corresponding value as a
361 numeric scalar. Returns "undef" if the number does not contain any
362 digits. Examples:
363
364 unformat_number('USD 12.95') yields 12.95
365 unformat_number('USD 12.00') yields 12
366 unformat_number('foobar') yields undef
367 unformat_number('1234-567@.8') yields 1234567.8
368
369 The value of "DECIMAL_POINT" is used to determine where to separate
370 the integer and decimal portions of the input. All other non-digit
371 characters, including but not limited to "INT_CURR_SYMBOL" and
372 "THOUSANDS_SEP", are removed.
373
374 If the number matches the pattern of "NEG_FORMAT" or there is a
375 ``-'' character before any of the digits, then a negative number is
376 returned.
377
378 If the number ends with the "KILO_SUFFIX", "KIBI_SUFFIX",
379 "MEGA_SUFFIX", "MEBI_SUFFIX", "GIGA_SUFFIX", or "GIBI_SUFFIX"
380 characters, then the number returned will be multiplied by the
381 appropriate multiple of 1024 (or if the base option is given, by
382 the multiple of that value) as appropriate. Examples:
383
384 unformat_number("4K", base => 1024) yields 4096
385 unformat_number("4K", base => 1000) yields 4000
386 unformat_number("4KiB", base => 1024) yields 4096
387 unformat_number("4G") yields 4294967296
388
390 Some systems, notably OpenBSD, may have incomplete locale support.
391 Using this module together with setlocale(3) in OpenBSD may therefore
392 not produce the intended results.
393
395 No known bugs at this time. Report bugs using the CPAN request tracker
396 at <https://rt.cpan.org/NoAuth/Bugs.html?Dist=Number-Format> or by
397 email to the author.
398
400 William R. Ward, SwPrAwM@cpan.org (remove "SPAM" before sending email,
401 leaving only my initials)
402
404 perl(1).
405
406
407
408perl v5.38.0 2023-07-21 Format(3)