vtils
Version:
一个面向业务的 JavaScript/TypeScript 实用程序库。
50 lines (48 loc) • 1.66 kB
JavaScript
"use strict";
exports.__esModule = true;
exports.formatNumber = formatNumber;
/**
* 格式化数字选项。
*/
/**
* 格式化数字。
*
* @param value 要格式化的数字
* @param options 选项
* @returns 返回格式化后的数值
* @example
* ```typescript
* formatNumber(1314.56789) // => '1,314.56789'
* formatNumber(1314.56789, { thousandsSeparator: ' ' }) // => '1 314.56789'
* formatNumber(1314.56789, { thousandthsSeparator: ',' }) // => '1,314.567,89'
* ```
*/
function formatNumber(value, options) {
var _ref = options || {},
_ref$thousandsSeparat = _ref.thousandsSeparator,
thousandsSeparator = _ref$thousandsSeparat === void 0 ? ',' : _ref$thousandsSeparat,
_ref$thousandthsSepar = _ref.thousandthsSeparator,
thousandthsSeparator = _ref$thousandthsSepar === void 0 ? '' : _ref$thousandthsSepar;
var _String$split = String(Math.abs(value)).split('.'),
integer = _String$split[0],
_String$split$ = _String$split[1],
decimal = _String$split$ === void 0 ? '' : _String$split$;
if (thousandsSeparator !== '') {
var result = '';
while (integer.length > 3) {
result = "" + thousandsSeparator + integer.slice(-3) + result;
integer = integer.slice(0, integer.length - 3);
}
integer = "" + integer + result;
}
if (thousandthsSeparator !== '') {
var _result = '';
while (decimal.length > 3) {
_result = "" + _result + decimal.slice(0, 3) + thousandthsSeparator;
decimal = decimal.slice(3);
}
decimal = "" + _result + decimal;
}
var numeral = "" + (value < 0 ? '-' : '') + integer + (decimal ? "." + decimal : '');
return numeral;
}