Thousands separator with php or Jquery javascript [duplicated]

1

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

    
asked by Marcela Faúndez 29.06.2017 в 23:25
source

3 answers

2

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);
}
    
answered by 30.06.2017 в 00:30
2

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 ( )

    
answered by 30.06.2017 в 00:25
0

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.

    
answered by 29.06.2017 в 23:35