Formatting numbers

DivKit has a built-in function and a method for formatting numbers, `decimalFormat'.

count.decimalFormat('#')
decimalFormat(count, '#')

Formatting template

The template can contain 4 characters: #, 0, ,, ..

The # indicates a number that can be omitted if it is not needed.

0 means the number that must necessarily be in the result. It will be filled in with a zero, if necessary, there is no significant digit.

Example:

1.decimalFormat('00') // -> '01'
123.decimalFormat('00') // -> '123'

, indicates the presence and position of the grouping. It can occur no more than 1 time in the template.

Example:

1234.decimalFormat('####') // -> '1234'
1234.decimalFormat('#,###') // -> '1,234'

. means a separator between an integer and a fractional part. It can occur no more than 1 time in the template.

Example:

1.decimalFormat('#.#') // -> '1'
1.decimalFormat('#.0') // -> '1.0'
1.2.decimalFormat('#.#') // -> '1.2'

A combination of different characters in the format

Example:

decimalFormat(1234567.89, '#,###.00') // -> '1,234,567.89'

You can read it like this:

  1. In the whole part, we output all the characters that are there, and after every 3 characters we draw a group separator
  2. We make at least 2 digits in the fractional part. There is always a point

Example:

decimalFormat(0.123456, '.00#') // -> '0.123'

It means "from 2 to 3 digits in the fractional part".

Rounding up

Rounded up by bank rounding (Round-Half-To-Even).

Rounded to the nearest even integer.

Example:

decimalFormat(0.5, '#') // -> '0'
decimalFormat(1.5, '#') // -> '2'
decimalFormat(2.5, '#') // -> '2'

Locales

The default version uses the current locale.

The locale affects the symbols for separating groups and for separating whole/fractional parts, as well as the numbers themselves.

In some cases, it is better to convey the locale explicitly:

decimalFormat(0.123456, '.00#', 'en-US') // -> '0.123'

The number of characters in a group is set by the template, not the locale!