fazlurr
1/15/2017 - 6:03 AM

Budget Format

Budget Format

// Format Budget
function formatBudget (budget, currency) {
	var budgetType = typeof budget;
	if (budgetType != "string") {
		budget = budget.toString();
	}

	// Remove character except . and ,
	budget = budget.replace(/[^\d.\d,-]/g, '');

	// Remove leading zeros
	budget = budget.replace(/^[0]+/g, '');

	var countryId = "";

	if (currency == "USD") {
		countryId = "us";
		// Remove all commas
		budget = budget.replace(/\,/g, '');

	} else if (currency == "IDR") {
		countryId = "id";
		// Remove all dots
		budget = budget.replace(/\./g, '');
		// Replace commas with dots, so it become a decimal
		budget = budget.replace(/\,/g, '.');
	}

	var formatOptions = { maximumFractionDigits: 2 };
	var formattedBudget = new Intl.NumberFormat( countryId, formatOptions ).format(budget);
	if ( formattedBudget == "NaN" ) {
		formattedBudget = 0;
	}
	return formattedBudget;
}