27 lines
807 B
JavaScript
27 lines
807 B
JavaScript
// @ts-check
|
|
|
|
/**
|
|
* # Get Number from any input
|
|
* @param {any} num input
|
|
* @param {number} [decimals] number of decimals to round to
|
|
* @returns {number} number or 0 in case of error
|
|
* @example
|
|
* numberfy("123") // 123
|
|
* numberfy("123.456") // 123
|
|
* numberfy("123.456", 2) // 123.46
|
|
* numberfy("123.456", 0) // 123
|
|
* numberfy("123.456", 3) // 123.456
|
|
*/
|
|
module.exports = function numberfy(num, decimals) {
|
|
try {
|
|
const numberfiedNum = Number(num);
|
|
if (typeof numberfiedNum !== "number") return 0;
|
|
if (isNaN(numberfiedNum)) return 0;
|
|
if (decimals) return Number(numberfiedNum.toFixed(decimals));
|
|
return Math.round(numberfiedNum);
|
|
} catch (/** @type {any} */ error) {
|
|
console.log(`Numberfy ERROR: ${error.message}`);
|
|
return 0;
|
|
}
|
|
};
|