datasquirel/package-shared/utils/numberfy.ts
2025-01-10 20:10:28 +01:00

22 lines
679 B
TypeScript

/**
* # Get Number from any input
* @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
*/
export default function numberfy(num: any, decimals: number): number {
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: any) {
console.log(`Numberfy ERROR: ${error.message}`);
return 0;
}
}