I'm trying to make a "peso" currency format for my input, where I want it to be formatted automatically when I enter with thousands separator (".") I have tried several codes and they do not work
I'm trying to make a "peso" currency format for my input, where I want it to be formatted automatically when I enter with thousands separator (".") I have tried several codes and they do not work
I use the following code in Javascript:
function formatNumber(num) {
if (!num || num == 'NaN') return '-';
if (num == 'Infinity') return '∞';
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 100;
num = Math.floor(num / 100).toString();
if (cents < 10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
return (((sign) ? '' : '-') + num + ',' + cents);
}
If you want to format the number while writing, you can add an event keyup
with either jquery or javascript that takes the value and using the Number.prototype.toLocaleString()
method format the number and add it to the value of the input.
Example done with javascript:
const number = document.querySelector('.number');
function formatNumber (n) {
n = String(n).replace(/\D/g, "");
return n === '' ? n : Number(n).toLocaleString();
}
number.addEventListener('keyup', (e) => {
const element = e.target;
const value = element.value;
element.value = formatNumber(value);
});
<input type="text" class="number">
I leave a link with documentation on the method toLocaleString ( )
With PHP: 2 decimals separated by commas and thousands per point.
$pesos = number_format($cantidad, 2,',','.');
You also have the money_format feature, which is currency specific.