@opengis/fastify-table
Version:
core-plugins
42 lines (36 loc) • 1.3 kB
JavaScript
/**
* Приведення чисел до стандартизованого виду
*
* @summary Форматування у число. Є можливість використання разом із значком span
* @priority 4
* @type helper
* @tag format
* @alias numFormat
* @example
* {{{num_format (coalesce rows.[0].attr 123.456) dec="2"}}}
* @example
* {{num_format (coalesce price 1) fixed="4"}}
* @example
* {{{num_format (math_sum multilang attr="total" fixed=2)}}}
* @param {String|Number} data Число для форматування
* @param {Object} span False - перевірка чи повернути у вигляді html з тега span
* @returns {String} Returns HTML
*/
export default function numFormat(data, options) {
const TP = typeof data;
const { dec, fixed, span } = options.hash;
const charAfterZero = dec || fixed;
if (!data || (TP !== 'number' && TP !== 'string')) return '';
if (TP === 'string') {
data = parseFloat(data.replace(',', '.'));
}
if (isNaN(data)) return '';
const num = (data)
.toFixed(charAfterZero || 2)
.replace(/(\d)(?=(\d{3})+\.)/g, '$1 ')
.split('.');
if (span) {
return num.map((el, i) => `<span class="part${i + 1}">${el}</span>`).join('.');
}
return num.join('.');
}