Files
BarangaySystem/resources/js/utils/currency.js
2026-06-06 18:43:00 +08:00

26 lines
775 B
JavaScript

/**
* Formats a number as Philippine Peso currency (PHP) with commas and optional decimals.
*
* @param {number} number - The numeric value to format
* @param {boolean} [withDecimal=true] - Whether to include decimal places
* @returns {string} - Formatted currency string (e.g., "P1,234.56")
*
* @example
* formatCurrency(1234.56) // "P1,234.56"
* formatCurrency(1234.56, false) // "P1,234"
*/
export function formatCurrency(number, withDecimal = true) {
if (isNaN(number)) return 'P0'
let [integerPart, decimalPart] = Number(number)
.toFixed(2)
.toString()
.split('.')
if (!withDecimal) decimalPart = ''
integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
return `P${integerPart}${decimalPart ? '.' + decimalPart : ''}`
}