frianH
frianH

Reputation: 7563

Thousands Separator with Javascript

I use oninput attribute to make the input field automatically to make thousand separator when inserting, and it worked.

But what I want achieve, it's allow to put dot . character too, because I want to get two decimal digits, so far this is my code doesn't work:

function separator(input) { 
  let nums = input.value.replace(/,/g, '');
  if(!nums)return;
  input.value = parseFloat(nums).toLocaleString(); 
}

function addition() {
  var number1 = document.getElementById('number1').value;
  var number2 = document.getElementById('number2').value;
  number1 = number1.replace(/[,]+/g, '');
  number2 = number2.replace(/[,]+/g, '');
  
  if (number1 == "")
    number1 = 0;
  if (number2 == "")
    number2 = 0;
    
  var result = parseFloat(number1) + parseFloat(number2);
  result = result.toFixed(2);
  if (!isNaN(result)) {
      document.getElementById('total').value = result;
  }
  document.getElementById('total').onchange();
}
<table>
  <tr>
    <td><input onkeyup="addition()" oninput="separator(this)" type="text" id="number1" placeholder="123,456.16"></td>
    <td>+</td>
    <td><input onkeyup="addition()" oninput="separator(this)" type="text" id="number2" placeholder="123,456.16"></td>
    <td>=</td>
    <td><input onchange="separator(this);" type="text" name="total" id="total" placeholder="total" readonly></td>
  </tr>
</table>

Even though I've set the input field with the attribute type="text", it still can't put a dot . character.

How to fix this issue?

Upvotes: 1

Views: 2144

Answers (2)

Hassan Khademi
Hassan Khademi

Reputation: 1390

function seprator(input) {
  let nums = input.value.replace(/,/g, '');
  if (!nums || nums.endsWith('.')) return;
  input.value = parseFloat(nums).toLocaleString();
}
<input type="text" id="inputSep" oninput="seprator(this)" placeholder="123,456,789"/>

codepen example link

Upvotes: 1

Impirator
Impirator

Reputation: 1432

Consider letting the browser do the work for you with Intl.NumberFormat

const $input = document.querySelector('input');
const $output = document.querySelector('div');

$input.addEventListener('input', (evt) => {
  $output.innerText = Intl.NumberFormat().format(evt.target.value);
});
<input>
<div></div>

You can customize many things about the format of the outputted number, and in your case you might like to tweak the minimumFractionDigits or maximumFractionDigits settings:

const $input = document.querySelector('input');
const $output = document.querySelector('div');

$input.addEventListener('input', (evt) => {
  $output.innerText = Intl.NumberFormat(undefined, {
    maximumFractionDigits: 2
  }).format(evt.target.value);
})
<input>
<div></div>

Upvotes: 1

Related Questions