📜 ⬆️ ⬇️

accounting.js - formatting numbers and currencies

In one of the projects I needed to implement currency switching and then reformatting the values ​​of the monetary amounts occurring on the page. As I often get, I implemented it and in a couple of weeks I came across a small library that makes it quite convenient to perform this operation.

It is called accounting.js .

The library can perform three formatting actions:

By default, the settings are in the format adopted in America: the currency is a dollar sign, the separator of the integer and fractional parts is a period, the separator of thousand digits is a comma.

formatNumber ()


A basic function that can be passed a number or an array of numbers and, at the output, obtains a number (or array) with thousands of digits separated and a fractional part of a given accuracy and a fractional separator - a comma.
')
Default settings:
accounting.formatNumber( 5318008 ); // 5,318,008

Three decimal places, thousands separation by space, fractional part is separated by comma:
accounting.formatNumber( 9876543 . 21 , 3 , " " , "," ); // 9 876 543,210

formatMoney ()


Formats numbers in the form of monetary amounts. In addition to the thousands separators, the precision and the fractional separator, the currency sign is set in accordance with the template.

Default:
accounting.formatMoney( 12345678 ); // $12,345,678.00

Currency sign - RUR, precision - two characters, thousands - space, fractional - comma, currency symbol after the number through the space:
accounting.formatMoney( 4999 . 99 , "RUR" , 2 , " " , "," , "%v %s" ); //4 999,99 RUR

formatColumn ()


The array of numbers is transferred to the function and it changes this array, complementing the numbers with spaces based on how many characters are in the maximum number and puts the currency sign either up to the augmented number or after, in accordance with the pattern. It is necessary to beautifully display the amount in the table.
accounting.formatColumn([ 123 , 12345 ], "$ " , 0 ); // ["$ 123", "$ 12,345"]

You can try various combinations of options in action in a small test on jsFiddle , or on the page of the library itself.

Source: https://habr.com/ru/post/131340/


All Articles