Add Commas to a Number in Jquery

Add comma to numbers every three digits

2016 Answer:

Javascript has this function, so no need for Jquery.

yournumber.toLocaleString("en");

add commas to a number in jQuery

Works on all browsers, this is all you need.

  function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:

$('#elementID').html(commaSeparateNumber(1234567890));

or

$('#inputID').val(commaSeparateNumber(1234567890));

However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.

  function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals

while (/(\d+)(\d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}

if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }

return val;
}

And in your jQuery, use like so:

$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});

Here's the jsFiddle.

Jquery adding commas to numbers

replace(',', '') only replaces first comma to to empty. You need a global comma replace. Try changing this line

this.value = addCommas(this.value.replace(',', ''));

To this:

this.value = addCommas(this.value.replace(/,/g, ''));

jQuery function to to format number with commas and decimal

You could accomplish this by splitting your string at the '.' character and then performing your comma-conversion on the first section only, as such:

function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}

ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696

Example

Can jQuery add commas while user typing numbers?

Run the code snippet to see it work

$('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, ",") ; });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><input class="number">

automatic adding comma every 3 digits during typing using jquery

Hello here is a script that I found in another topic.

script credit: http://phpjs.org/functions/number_format/

function number_format (number, decimals, dec_point, thousands_sep) {    // Strip all characters but numerical ones.    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');    var n = !isFinite(+number) ? 0 : +number,        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,        s = '',        toFixedFix = function (n, prec) {            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;        };    // Fix for IE parseFloat(0.55).toFixed(0) = 0;    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }    if ((s[1] || '').length < prec) {        s[1] = s[1] || '';        s[1] += new Array(prec - s[1].length + 1).join('0');    }    return s.join(dec);}
<input type="number" value="0" oninput="document.getElementById('result').innerHTML = number_format(this.value, 0, ',', ' ')"><br><span>Result: <b id="result">0</b> </span>

Adding comma to number with jQuery, NaN

instead of var curVal = $("#propertyValueSliderValue").val(); in minus function,

remove the commas and then parse it.

var curVal = $("#propertyValueSliderValue").val();
curVal = parseInt(curVal.replace(/,/g, ""))

best approach in adding a comma to a number like 123,456.78 in jquery

The problem is that parseFloat fails to correctly parse the value from the total cost textbox because it contains one or more ,. You need to remove the , from the string before parsing to float. You can remove any ,'s by calling .replace(/,/g,'') on the textbox value in the calculateSubTotal function.

It seems that for some values the function commaSeparateNumber doesn't work as expected. I removed it from the snippet below and replaced it with toLocaleString() which takes parameters for locale and minimum/maximum fraction digits .toLocalString("en-US", { maximumFractionDigits: 2}). Set the locale to one you know uses , to separate thousands. If you know that won't be an issue you can pass undefined for the locale.

Your snippet has been updated below:

var rowCount = 1;    $('#add').click(function() {    rowCount++;    $('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]"  for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');});
// Add a generic event listener for any change on quantity or price classed inputs$("#orders").on('input', 'input.quantity,input.product_price', function() { getTotalCost($(this).attr("for"));});
$(document).on('click', '.btn_remove', function() { var button_id = $(this).attr('id'); $('#row'+button_id+'').remove();});
// Using a new index rather than your global variable ifunction getTotalCost(ind) { var qty = $('#quantity_'+ind).val(); var price = $('#product_price_'+ind).val(); var totNumber = (qty * price); // .toLocaleString var tot = totNumber.toLocaleString("en-US", { maximumFractionDigits: 2}); $('#total_cost_'+ind).val(tot); calculateSubTotal();}
function calculateSubTotal() { var subtotal = 0; $('.total_cost').each(function() { // replace ',' here subtotal += parseFloat($(this).val().replace(/,/g,'')); }); // toLocaleString $('#subtotal').val(subtotal.toLocaleString("en-US", { maximumFractionDigits: 2}));}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html>
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script></head>
<body> <div class="col-md-12"> <div class="line line-dashed line-lg pull-in"></div> <div class="row"> <table class="table table-bordered" id="orders"> <tr> <th>Price</th> <th>Quantity</th> <th>Total Cost</th> <th> </th> </tr> <tr> <td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost --> <td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td> <td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td> <td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td> </tr> </table> <input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/> </div> </div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div> <div class="col-md-12 nopadding"> <div class="col-md-4 col-md-offset-4 pull-right nopadding"> <div class="col-md-8 pull-right nopadding"> <div class="form-group"> <td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td> </div> </div> <div class="col-md-3 pull-right"> <div class="form-group"> <label>Subtotal</label> </div> </div> </div> </div></body></html>

How to add commas format in number after page load using jquery

As far as I know, you can't do this using pure CSS.

However, you could use a JavaScript function to add commas for you.

I have used this one in the past:

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

Reference

And then do your jquery:

$(function(){
$(".format").each(function(c, obj){
$(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
});
});

JSfiddle Demonstration:



Related Topics



Leave a reply



Submit