Rand Stats

Intl::Format::Number

zef:guifa

Intl::Format::Number

A module for formatting numbers in a localized manner

To use, simply say

use Intl::Format::Number;

# Assuming user-language is 'en' (English)
say format-number 4834853;  # 4,834,853
say format-number 12.394;   # 12.394
say format-number 1/3;      # 0.333333333333333

# A separate call can get a number formatter which allows you to specify more options
my $formatter = local-number-formatter('en', :minimum-significant-digits<2>); 

It's that easy :-)

Currently supports percent, permille and scientific formatting in addition to the basic number format for languages with decimal number systems (sorry ancient Romans or Mayans!).

Other formatting styles (like compact) styles and options specified in TR 35 / CLDR, are NYI but will be available soon (current will be available via a separate module).

Performance is about an order of magnitude slower than .Str for most formatting, and I continue to try to optimize it farther. Balancing performance with the ability to, e.g., format a FatRat of several thousand digits, isn't easy :-)

Options

The Raku-defined variable $*TOLERANCE is used in the case of extremely long decimals (e.g. any repeating decimal like 1/3). Raku defaults it to 1e-15 (thus providing 15 digits of decimals) but you can set it to any number. You are highly advised not to set it to 0 as this may cause an infinite loop unless. (In the future, setting the maximum fractional digits to Inf and $*TOLERANCE to 0 will generate an error).

Basic options

Number formatter options (for use with get-number-formatter)

optiondescriptionexample
maximum-integer-digitsNo more whole digits than thiswhen 2
1234 yields 34
minimum-integer-digitsPad with zeros to have at least this manywhen 4
12 yields 0012
maximum-fractional-digitsNo more decimal digits than thiswhen 2
1.2345 yields 1.23
minimum-fractional-digitsAdd trailing zeros to have at least this manywhen 3
1.2 yields 1.200
maximum-significant-digitsLimits the amount of significant digits usedwhen 2
1234 yields 1200
minimum-significant-digitsAdd trailing zeros if necessarywhen 3
1 yields 1.00
show-decimalForces the decimal to be shownwhen True
1 yields 1.
show-signShows the sign regardless polaritywhen True
1 yields +1
symbolsAdjusts the symbols used in formatting.
number-systemSet the digits used. Must be a CLDR code.when arab, 1234 yields ١٢٣٤
rastReturns a RakuAST node instead

If significant digits are specified, then the integral/fractional digits are currently ignored. Presently, the RakuAST node generated is a RakuAST::Sub. Additional documentation on it will be included in future updates to improve its integration with other modules.

Todo

Version history

© 2020-2023 Matthew Stephen Stuckwisch. Licensed under the Artistic License 2.0.