Html формат вывода числа

Natively Format JavaScript Numbers

When I’ve needed to format numbers in JavaScript I usually used Number.prototype.toFixed() , found a 3rd party library, or manually manipulated the number to suite my needs. However, with modern browsers, there’s a lot of really interesting capabilities you could start using with Number.prototype.toLocaleString() or Intl.NumberFormat . The following is a screenshot of the cross browser support from caniuse.com.

NOTE: Although the support looks pretty good from the above image, some of the options ( compactDisplay , currencySign , notation , signDisplay , unit , and unitDisplay ) are not supported in Safari (see compat table from MDN). However, thankfully there’s a polyfill you can use from Format.JS.

Quick 6 minute Overview

Number.prototype.toLocaleString()

The Number.prototype.toLocaleString() method takes two optional parameters of locales and options . If you don’t pass either, you’ll get the browser’s default locale. We’ll focus on the options parameter in the following sections.

const number = 12345.6789; console.log(number.toLocaleString()); // 12,345.679 (defaults to the "en-US" locale in my case) console.log(number.toLocaleString('de-DE')); // 12.345,679 

Currency Format

Formatting numbers is great and all, but what about fancy stuff like money. Well, that’s were the 2nd optional options parameter comes into play. If you supply a property of < style: "currency" >and a valid currency (an ISO 4217 currency code) then you’ll get a nicely formatted currency with locale support!

NOTE: There is no default currency code, so you’ll get an error if you don’t provide one.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  style: 'currency', currency: 'USD', >), ); // $12,345.68 console.log( number.toLocaleString('de-DE',  style: 'currency', currency: 'EUR', >), ); // 12.345,68 € console.log( number.toLocaleString('ja-JP',  style: 'currency', currency: 'JPY', >), ); // ¥12,346 

Significant Digits

Sometimes you want to control how many digits are significant in a number. You might think of this as Frontend Estimation. You can provide a minimumSignificantDigits (defaults to 1 ) or a maximumSignificantDigits (defaults to 21 ).

const number = 12345.6789; console.log( number.toLocaleString('en-US',  maximumSignificantDigits: 1, >), ); // 10,000 console.log( number.toLocaleString('fr-FR',  maximumSignificantDigits: 3, >), ); // 12 300 

Unit Support

Unit support is one of those things that I wouldn’t have expected to be a feature, but is pretty cool to have. You can mix and match locales along with units of measurement. You can find a full list of possible units from the ECMAScript specification. You can also provide a unitDisplay of long , short (default), or narrow to control how verbose the unit is displayed.

NOTE: This is one of those features that is not supported by Safari. Also there is no default value for unit , so if style is set to unit then one must be provided.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  style: 'unit', unit: 'mile-per-hour', >), ); // 12,345.679 mph console.log( number.toLocaleString('fr-FR',  style: 'unit', unit: 'liter', unitDisplay: 'long', >), ); // 12 345,679 litres 

Compact Notation

I found this amusing when I realized this feature existed. Not too long ago I needed something like this to abbreviate large numbers. I ended up finding a snippet of code online to get the job done, but now I know I could have used < notation: "compact" >! It also takes an optional compactDisplay that can be set to short (default) or long .

NOTE: This is one of those features that is not supported in Safari.

const number = 12345.6789; console.log( number.toLocaleString('en-US',  notation: 'compact', compactDisplay: 'short', >), ); // 12K console.log( number.toLocaleString('en-US',  notation: 'compact', compactDisplay: 'long', >), ); // 12 thousand 

Percents

Having percent support is probably not a surprise to you, but it is handy to have especially since it is locale aware (as all the other options are). It gets a little bit nicer because you can also provide other options such as minimumFractionDigits (defaults to 0 or 2 for currency) or maximumFractionDigits to control how many fraction digits to use.

const number = 0.1234; console.log( number.toLocaleString('en-US',  style: 'percent', minimumFractionDigits: 2, >), ); // 12.34% 

Accounting

I don’t typically show negative currency with parenthesis, but apparently that is a common approach for those that do a lot of accounting. I probably won’t use this, but it’s good to know that it’s an option in case I ever do.

NOTE: This is one of those features that is not supported in Safari.

const number = -123.456; console.log( number.toLocaleString('en-US',  style: 'currency', currency: 'USD', currencySign: 'accounting', signDisplay: 'always', >), ); // ($123.46) 

Intl.NumberFormat

So, instead of using Number.prototype.toLocaleString() you could also use the Intl.NumberFormat constructor and then call the format method to format your numbers. However, that might confusing and may make you question which technique you should use. If you find yourself needing to format many numbers over and over again with the same locale and same options, then using Intl.NumberFormat is preferable for performance reasons.

«When formatting large numbers of numbers, it is better to create a NumberFormat object and use the function provided by its NumberFormat.format property.» —Number.prototype.toLocaleString()

const numberFormat = new Intl.NumberFormat('en-US',  style: 'unit', unit: 'mile-per-hour', >); console.log(numberFormat.format(12345.6789)); // 12,345.679 mph console.log(numberFormat.format(2345.67891)); // 2,345.679 mph 

Playground

For more information about all of these options and browser support, check out the Intl.NumberFormat() constructor page on MDN.

Источник

Html формат вывода числа

В разных культурах используются различные подходы к отображению чисел. Например, в одних культурах (в частности, в США, Великобритании) в качестве разделителя целой и дробной части применяется точка, а в других культурах — запятая. Аналогично разделителем между разрядами может служить как точка, так и запятая. И объект Intl.NumberFormat позволяет нам локализовать числительные под нужную культуру.

Конструктор Intl.NumberFormat может принимать два параметра:

Intl.NumberFormat([locales[, options]])

Параметр locales представляет код языка в формате BCP 47 или набор языковых кодов.

Параметр options представляет дополнительный набор опций:

  • localeMatcher : алгоритм поиска соответствий. Может принимать два значения: «lookup» и «best fit» . Значение по умолчанию — «best fit» .
  • compactDisplay : применяется, если параметр notation равен «compact» . Возможные значения: «long» и «short» (значение по умолчанию)
  • currency : задает валюту, которая применяется для форматирования. В качестве значения принимает код валюты в формате ISO 4217, например, «USD» (доллар США), «EUR» (евро) и т.д. Этот параметр необходимо обязательно указать, если параметр style имеет значение «currency» .
  • currencyDisplay : указывает, как отображать валюту. Возможные значения:
    • «symbol» : применяется символ валюты (например, € для евро). Значение по умолчанию
    • «narrowSymbol» : применяется сокращенное обозначение валюты (например, «$100» вместо «US$100»)
    • «code» : применяется код валюты
    • «name» : применяется локализованное название валюты (например, «dollar»)
    • «standard» : применяется для форматирования обычных чисел. Значение по умолчанию
    • «scientific» : возвращает порядок величины для форматируемого числа
    • «engineering» : возвращает значение в экспоненциальной нотации
    • «compact» : для представления экспоненциальной записи применяется строка
    • «auto» : знак отображается только для отрицательных чисел. Значение по умолчанию
    • «never» : знак никогда не отображается
    • «always» : знак отображается всегда
    • «exceptZero» : знак отображается для всех чисел, кроме нуля
    • «decimal» : для форматирования обычных чисел. Значение по умолчанию
    • «currency» : для форматирования валюты
    • «percent» : для форматирования процентов
    • «unit» : для форматирования единиц измерения
    • «long» : полная форма (например, 16 litres )
    • «short» : сокращенная форма (например, 16 l ). Значение по умолчанию
    • «narrow» : сжатая форма (например, 16l )

    Для форматирования числа объект Intl.NumberFormat предоставляет метод format() , в который передается форматируемое число и который возвращает отформатированное число в виде строки.

    Локализуем число 5500,67 на разные языки:

    const amount = 5500.67; const en = new Intl.NumberFormat("en").format(amount); const ru = new Intl.NumberFormat("ru").format(amount); const de = new Intl.NumberFormat("de").format(amount); console.log(en); // 5,500.67 console.log(ru); // 5 500,67 console.log(de); // 5.500,67

    По умолчанию для форматирования чисел применяется параметр . Также мы могли бы его явно применить:

    const amount = 5500.67; const ru = new Intl.NumberFormat("ru", ).format(amount); // то же самое, что и // const ru = new Intl.NumberFormat("ru").format(amount); console.log(ru); // 5 500,67

    Форматирование процентов

    В разных культурах может отличаться написание процентов. Для локализации процентов применяется значение

    const value = 0.851; const en = new Intl.NumberFormat("en", ).format(value); const ru = new Intl.NumberFormat("ru", ).format(value); const tr = new Intl.NumberFormat("tr", ).format(value); console.log(en); // 85% console.log(ru); // 85 % console.log(tr); // %85

    Вывод дробной части

    Однако в примере выше мы видим, что теряется дробная часть. Чтобы исправить положение, мы можем использовать параметр minimumFractionDigits , который задает количество знаков в дробной части:

    const value = 0.851; const en = new Intl.NumberFormat("en", ).format(value); const ru = new Intl.NumberFormat("ru", ).format(value); console.log(en); // 85.10% console.log(ru); // 85,10 %

    Форматирование валюты

    Для форматирования валюты применяется параметр style: «currency» , при этом также надо указать параметр currency , которому передается код валюты:

    const value = 85.1; const en = new Intl.NumberFormat("en", ).format(value); const ru = new Intl.NumberFormat("ru", ).format(value); const tr = new Intl.NumberFormat("tr", ).format(value); console.log(en); // $85.10 console.log(ru); // 85,10 $ console.log(tr); // $85,10
    const value = 85.1; const usd = new Intl.NumberFormat("ru", ).format(value); const euro = new Intl.NumberFormat("ru", ).format(value); const rub = new Intl.NumberFormat("ru", ).format(value); console.log(usd); // 85,10 $ console.log(euro); // 85,10 € console.log(rub); // 85,10 ₽

    По умолчанию выводится символ валюты, однако значение currencyDisplay: «name» позволяет вывести локализованное название валюты:

    const value = 85; const usd = new Intl.NumberFormat("ru", ).format(value); const euro = new Intl.NumberFormat("ru", ).format(value); const rub = new Intl.NumberFormat("ru", ).format(value); console.log(usd); // 85 долларов США console.log(euro); // 85,00 евро console.log(rub); // 85,00 российского рубля

    Форматирование единиц измерения

    Для форматирования единиц измерения применяется значение style: «unit» . При этом также необходимо указать название единицы измерения с помощью параметра unit :

    const value = 85; const en = new Intl.NumberFormat("en", ).format(value); const ru = new Intl.NumberFormat("ru", ).format(value); const zh = new Intl.NumberFormat("zh", ).format(value); console.log(en); // 85 L console.log(ru); // 85 л console.log(zh); // 85升

    По умолчанию применяет сокращенная форма наименования валюты. С помощью значения unitDisplay: «long» можно задать вывод полного наименования:

    const value = 85; const longLiter = new Intl.NumberFormat("ru", ).format(value); const shortLiter = new Intl.NumberFormat("ru", ).format(value); console.log(longLiter); // 85 литров console.log(shortLiter); // 85 л

    Еще несколько примеров с форматированием разных единиц измерения:

    const value = 85; const kilobyte = new Intl.NumberFormat("ru", ).format(value); const meter = new Intl.NumberFormat("ru", ).format(value); const gram = new Intl.NumberFormat("ru", ).format(value); console.log(kilobyte); // 85 килобайт console.log(meter); // 85 метров console.log(gram); // 85 грамм

    Источник

    Читайте также:  Find python второе вхождение
Оцените статью