Format(3)
π Format(3) β Number::Format β User Contributed Perl Documentation π
πΈ NAME πΈ
Number::Format β Perl extension for formatting numbers. Thatβs the whole pitch, bestie. β¨
β¨ 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);
$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);
π§Έ REQUIRES π§Έ
- Perl, version 5.8 or higher.
POSIX.pmto determine locale settings.Carp.pmis used for some error reporting.
π DESCRIPTION π
These functions are your little number-glow-up kit: they format numbers in a way thatβs suitable for showing to an actual human. π«Ά
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 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β likeTHOUSANDS_SEP, but used forformat_price.MON_DECIMAL_POINTβ likeDECIMAL_POINT, but used forformat_price.INT_CURR_SYMBOLβ character(s) denoting currency (seeformat_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).KILO_SUFFIXβ suffix to add whenformat_bytesformats kilobytes (trad).MEGA_SUFFIXβ same idea, but for megabytes (trad).GIGA_SUFFIXβ same idea, but for gigabytes (trad).KIBI_SUFFIXβ suffix to add whenformat_bytesformats kibibytes (iec).MEBI_SUFFIXβ same idea, but for mebibytes (iec).GIBI_SUFFIXβ same idea, but for gibibytes (iec).
They may be specified in upper or lower case, with or without a leading hyphen (-).
If THOUSANDS_SEP is set to the empty string, format_number will not insert any separators.
The defaults for THOUSANDS_SEP, DECIMAL_POINT, MON_THOUSANDS_SEP, MON_DECIMAL_POINT, and INT_CURR_SYMBOL come from the POSIX locale information (see perllocale). If your POSIX locale does not provide MON_THOUSANDS_SEP and/or MON_DECIMAL_POINT fields, then the THOUSANDS_SEP and/or 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 <SwPrAwM@cpan.org> (remove "SPAM" to get correct email address) for help.
If any of the above parameters are not specified when you invoke new(), then the values are taken from package global variables of the same name (e.g. $DECIMAL_POINT is the default for the DECIMAL_POINT parameter). If you use the :vars keyword on your use Number::Format line (see non-object-oriented example below) you will import those variables into your namespace 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'
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 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 DECIMAL_FILL and DECIMAL_DIGITS values are not set by the Locale system, but are definable by the user. They affect the output of format_number(). Setting DECIMAL_DIGITS is like giving that value as the $precision argument to that function. Setting DECIMAL_FILL to a true value causes format_number() to append zeroes to the right of the decimal digits until the length is the specified number of digits.
NEG_FORMAT is only used by 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. format_number() and format_price() utilize this feature by calling format_negative() if the number was less than 0.
KILO_SUFFIX, MEGA_SUFFIX, and GIGA_SUFFIX are used by 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.
KIBI_SUFFIX, MEBI_SUFFIX, and GIBI_SUFFIX are used by 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 DECIMAL_POINT and THOUSANDS_SEP are that they must not be digits and must not be identical. There are no restrictions on 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);
π 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 use Number::Format statement. To export all functions defined herein, use the special tag :subs. To export the variables, use the special tag :vars; to export both subs and vars you can use the tag :all.
π οΈ METHODS π οΈ
π« 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');
π’ round($number, $precision)
Rounds the number to the specified precision. If $precision is omitted, the value of the 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 $precision may be any integer, positive or negative. Examples:
round(3.14159) yields 3.14
round(3.14159, 4) yields 3.1416
round(42.00, 4) yields 42
round(1234, -2) 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 DECIMAL_POINT and THOUSANDS_SEP variables are ignored. To format your number using the DECIMAL_POINT and THOUSANDS_SEP variables, use format_number() instead.
πΈ format_number($number, $precision, $trailing_zeroes)
Formats a number by adding THOUSANDS_SEP between each set of 3 digits to the left of the decimal point, substituting DECIMAL_POINT for the decimal point, and rounding to the specified precision using round(). Note that $precision is a maximum precision specifier; trailing zeroes will only appear in the output if $trailing_zeroes is provided, or the parameter DECIMAL_FILL is set, with a value that is true (not zero, undef, or the empty string). If $precision is omitted, the value of the DECIMAL_DIGITS parameter (default value of 2) is used.
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'
Of course the output would have your values of THOUSANDS_SEP and DECIMAL_POINT instead of ',' and '.' respectively.
π€ format_negative($number, $picture)
Formats a negative number. Picture should be a string that contains the letter "x" where the number should be inserted. For example, for standard negative numbers you might use "-x", while for accounting purposes you might use "(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.
πΌοΈ format_picture($number, $picture)
Returns a string based on $picture with the "#" characters replaced by digits from $number. If the length of the integer part of $number is too large to fit, the "#" characters are replaced with asterisks ("*") instead. Examples:
okay so the format_picture examples are literally this π
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 , and . you see in those picture strings should match THOUSANDS_SEP and DECIMAL_POINT respectively, or it won't work right. but like, the THOUSANDS_SEP chars in $picture don't have to land every three digits β the only thing this function does with that variable is strip leading commas (see the first example up there). and you cannot have more than one DECIMAL_POINT in $picture, periodt.
NEG_FORMAT decides how negative numbers show up. the side effect? the output of this function may have unexpected spaces before and/or after the number π. that's necessary so positive and negative numbers get formatted into the same-size space. if you're only using positive numbers and want to dodge the whole problem, set NEG_FORMAT to "x".
format_price($number, $precision, $symbol) ποΈ
returns a string with $number formatted kinda like format_number(), except the decimal part may get trailing zeroes padded on so it's exactly $precision characters long, and the currency string gets prefixed. slay.
$symbol can be INT_CURR_SYMBOL or CURRENCY_SYMBOL (case insensitive) to use that attribute of the object, or just a string holding the symbol you want. default is INT_CURR_SYMBOL if the arg is undefined or not given. if it's set to the empty string, or set to undef while the object's INT_CURR_SYMBOL attribute is the empty string, then no currency gets added at all.
if $precision isn't provided, the default of 2 is used. examples:
format_price(12.95) yields 'USD 12.95'
format_price(12) yields 'USD 12.00'
format_price(12, 3) yields '12.000'
the third example assumes INT_CURR_SYMBOL is the empty string.
format_bytes($number, %options) / format_bytes($number, $precision) # deprecated π¦
format_bytes($number, %options)
format_bytes($number, $precision) # deprecated
returns a string with $number formatted similarly to format_number(), except big numbers may be abbreviated with a suffix for 1024, 1,048,576, or 1,073,741,824 bytes. the suffix can be the traditional K, M, or G (default), or the IEC standard 60027 KiB, MiB, or GiB depending on the mode option.
negative values will result in an error π¨.
the second parameter can be a hash that sets options, or a number. using a number here is deprecated and will generate a warning; early versions of Number::Format only allowed a numeric value. a future release of Number::Format will change this warning to an error. new code should use a hash instead to set options. if it's a number, it sets the precision option.
valid options are:
precisionβ sets the precision for displaying numbers. if not provided, default is2. examples:
format_bytes(12.95) yields '12.95'
format_bytes(12.95, precision => 0) yields '13'
format_bytes(2048) yields '2K'
format_bytes(2048, mode => "iec") yields '2KiB'
format_bytes(9999999) yields '9.54M'
format_bytes(9999999, precision => 1) yields '9.5M'
unitβ sets the default units used for the results. default is to figure it out automatically so the string stays as short as possible. in other words, numbers greater than or equal to1024(or whatever number thebaseoption gives, q.v.) get divided by1024and$KILO_SUFFIXor$KIBI_SUFFIXadded; if they're greater than or equal to1048576(1024*1024), they get divided by1048576and$MEGA_SUFFIXor$MEBI_SUFFIXappended; etc.
however, if a value is given for unit, it uses that instead. the first letter (case-insensitive) of the value tells you the threshold for conversion; acceptable values are G (giga/gibi), M (mega/mebi), K (kilo/kibi), or A (automatic, the default). for example:
format_bytes(1048576, unit => 'K') yields '1,024K'
instead of '1M'
note that the valid values for this option don't change even when the suffix configuration variables have been changed.
baseβ sets the number at which$KILO_SUFFIXgets added. default is1024. set it to any value; the only other useful value is probably1000, because hard disk manufacturers use that number to make their disks sound bigger than they really are π. if themode(see below) is set to"iec"or"iec60027", then setting thebaseoption results in an error.modeβ traditionally, bytes have been given in SI (metric) units like "kilo" and "mega" even though they represent powers of 2 (1024, etc.) rather than powers of 10 (1000, etc.). this "binary prefix" causes so much confusion in consumer products where "GB" may mean either1,048,576or1,000,000, for example. the International Electrotechnical Commission made standard IEC 60027 to introduce prefixesKi,Mi,Gi, etc. ("kibibytes," "mebibytes," "gibibytes," etc.) to remove this confusion. specify amodeoption with either"traditional"or"iec60027"(or abbreviate as"trad"or"iec") to say which type of binary prefix you wantformat_bytesto use. for backward compatibility,"traditional"is the default. seehttp://en.wikipedia.org/wiki/Binary_prefixfor more info.
unformat_number($formatted) π
converts a string as returned by format_number(), format_price(), or format_picture(), and returns the corresponding value as a numeric scalar. returns "undef" if the number has no digits at all. examples:
unformat_number('USD 12.95') yields 12.95
unformat_number('USD 12.00') yields 12
unformat_number('foobar') yields undef
unformat_number('1234-567@.8') yields 1234567.8
the value of DECIMAL_POINT tells it where to split the integer and decimal parts of the input. all other non-digit characters β including but not limited to INT_CURR_SYMBOL and THOUSANDS_SEP β get removed.
if the number matches the pattern of NEG_FORMAT, or there's a - character before any of the digits, then you get a negative number back.
if the number ends with the KILO_SUFFIX, KIBI_SUFFIX, MEGA_SUFFIX, MEBI_SUFFIX, GIGA_SUFFIX, or GIBI_SUFFIX characters, then the returned number gets multiplied by the appropriate multiple of 1024 (or by the multiple of the base option value, if that's given) as appropriate. examples:
unformat_number("4K", base => 1024) yields 4096
unformat_number("4K", base => 1000) yields 4000
unformat_number("4KiB", base => 1024) yields 4096
unformat_number("4G") yields 4294967296
π CAVEATS π
some systems β notably OpenBSD β may have incomplete locale support π¬. so using this module together with setlocale(3) on OpenBSD might not produce the intended results. not a vibe, but now you know.
π BUGS π
no known bugs at this time. if you find one, report it using the CPAN request tracker at https://rt.cpan.org/NoAuth/Bugs.html?Dist=Number-Format or by email to the author π«Ά.
π AUTHOR π
William R. Ward, SwPrAwM@cpan.org (remove "SPAM" before sending email, leaving only my initials) π
π SEE ALSO π
xoxo bestie π this page is from perl v5.42.0, dated 2023-05-26 β mwah πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: perl-Number-Format 1.76-bp160.1.11 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms