-1

I have a text field like this

The text field

enter image description here

The data is took from database, now I want to add comma into it every 3 digits, i want to solve it with jquery, is that possible

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
Vinh Nguyễn
  • 71
  • 2
  • 10
  • 1
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – dave Sep 28 '17 at 04:53

3 Answers3

7

Solution1: you could simply use Number.toLocaleString()

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();

Solution 2: You could use regex to a make simple jquery plugin

$.fn.digits = function() {
  return this.each(function() {
    $(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
  })
}

$("span").digits();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="numbers">3456754323456432</span>
Keshan Nageswaran
  • 8,060
  • 3
  • 28
  • 45
1

Here is the jsfiddle for you to do inline formatting as you type. https://jsfiddle.net/wm61qzsm/

js code:

$('input.number').keyup(function(event) {

  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40) return;

  // format number
  $(this).val(function(index, value) {
    return value
    .replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    ;
  });
});
Optional
  • 4,387
  • 4
  • 27
  • 45
0

You could parse the input to a float and use number.toLocalString();

var data = $("#getInfo");
var dataParse = parseFloat(data.val());

dataParse = dataParse.toLocaleString();

$("#getInfoNew").val(dataParse);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
BEFORE<input type="text" id="getInfo" value="14000000,0"><br>
AFTER<input type="text" id="getInfoNew" value="">
Icewine
  • 1,851
  • 1
  • 12
  • 22