datasquirel/package-shared/utils/numberfy.js

27 lines
807 B
JavaScript
Raw Normal View History

2024-12-12 05:43:07 +00:00
// @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;
}
};