nambas
Version:
A simple JS library to format numbers using in-built Intl.NumberFormat
50 lines • 2.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = format;
const formatter_1 = __importDefault(require("./formatter"));
const types_1 = require("./types");
function format(value, options) {
var _a, _b, _c, _d, _e;
let decimalSymbol = '.';
let style = types_1.EStyle.DECIMAL;
let nambaFormat;
if (typeof value === 'string') {
value = Number(value);
}
if (typeof options === 'string') {
nambaFormat = options;
const knownOptions = (0, formatter_1.default)(nambaFormat);
if ((_a = Object.keys(knownOptions)) === null || _a === void 0 ? void 0 : _a.length) {
options = knownOptions;
}
else {
// handle decimals
if (nambaFormat.indexOf(',') > nambaFormat.indexOf('.')) {
decimalSymbol = ',';
}
const decimals = nambaFormat.split(decimalSymbol);
options = {
decimals: (_c = (_b = decimals === null || decimals === void 0 ? void 0 : decimals[decimals.length - 1]) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0,
};
// determine percent style
if (nambaFormat.includes('%')) {
options.style = types_1.EStyle.PERCENT;
}
}
}
if (options === null || options === void 0 ? void 0 : options.currency) {
style = types_1.EStyle.CURRENCY;
}
if (options === null || options === void 0 ? void 0 : options.style) {
style = options === null || options === void 0 ? void 0 : options.style;
}
return new Intl.NumberFormat((_d = options === null || options === void 0 ? void 0 : options.locale) !== null && _d !== void 0 ? _d : 'en-US', {
style,
currency: options === null || options === void 0 ? void 0 : options.currency,
maximumFractionDigits: (_e = options === null || options === void 0 ? void 0 : options.decimals) !== null && _e !== void 0 ? _e : 0,
}).format(value);
}
//# sourceMappingURL=format.js.map