1

I have a number input field like the following:

<input type="number">

Right now, if I write a number, it is displayed like this:

123.456

I would like to display it with a comma separator, but apparently nothing is working!

The desired result is:

123,456

I tried lang="nb", setting a pattern="\d+,\d+" type="text", but none worked.

Both Javascript and HTML answers are welcome!

Nano
  • 814
  • 2
  • 13
  • 30

3 Answers3

1

You can use toLocaleString

 var number = 123456.789;

    // German uses comma as decimal separator and period for thousands
    console.log(number.toLocaleString('de-DE'));
    // → 123.456,789

    // Arabic in most Arabic speaking countries uses Eastern Arabic digits
    console.log(number.toLocaleString('ar-EG'));
    // → ١٢٣٤٥٦٫٧٨٩

    // India uses thousands/lakh/crore separators
    console.log(number.toLocaleString('en-IN'));
    // → 1,23,456.789

    // the nu extension key requests a numbering system, e.g. Chinese decimal
    console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
    // → 一二三,四五六.七八九

    // when requesting a language that may not be supported, such as
    // Balinese, include a fallback language, in this case Indonesian
    console.log(number.toLocaleString(['ban', 'id']));
    // → 123.456,789
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
0

I would allow the user to type both kinds of punctuation, and use an event listener to replace all periods in the input value with commas.

When you need to get that value back as a JavaScript number, you can simply call getValueAsNumber with the input element you want to use.

var input = document.querySelector('input')

input.addEventListener('change', function() {
  this.value = this.value.replace(/\./g, ',')
})

function getValueAsNumber(input) {
  return +input.value.replace(/,/g, '.')
}
<label>
  Type a number!
  <input lang="nb" type="text" pattern="\d*[,.]\d+|\d+(?:[,.]\d*)?">
</label>

<button onclick="console.log(getValueAsNumber(input))">
  What number did I type?
</button>
gyre
  • 16,369
  • 3
  • 37
  • 47
0

As you want this in a input field, you can use Javascript code to do this. Here is a demo code. I have done this on a keyup function you can do this on change too.

https://jsfiddle.net/Dheer_Jangra/rfx34op8/2/

var x;

$('#number').on("keyup", function() {
  x = removeCommas(this.value);
  this.value = addCommas(x);
});

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function removeCommas(value){
  value=value.replace(/\,/g,'');
  value=parseInt(value,10);
  return value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number"/>
Dheer Jangra
  • 63
  • 1
  • 2
  • 10