This requires two operations...
Parse the number string into a
Numberinstanceconst actualNumber = +number.replace(/,/g, '') // produces 4500.02734Format the string to a given locale with a maximum of 2 decimal places
const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})
var number = '4,500.02734'
const actualNumber = +number.replace(/,/g, '')
const formatted = actualNumber.toLocaleString('en-US', {maximumFractionDigits: 2})
document.write(formatted)
You can use this simple function that will convert your number to comma separated value and decimal number round off as well.
var number = 5000000.245;
document.write(format_number(number));
function format_number(n) {
return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}
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
I use accounting.js lib:
accounting.format(1136.6696, 4) // 1,136.6696
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
Maybe something like this, where you could select more than one element if you'd like?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
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.
Number(10000).toLocaleString('en'); // "10,000"
$(this).temp1() looks particularly out of place, I think you just meant to use the temp1 variable. Since it's already a number, you don't need to use parseFloat on it either:
$("#discount").change(function() {
var list = $("#list").val();
var discount = $("#discount").val();
var price = $("#price");
var temp = discount * list;
var temp1 = list - temp;
var total = temp1.toFixed(2);
price.val(total);
});
I would suggest you to convert strings to number first before calculation. For example,
var list = parseFloat($("#list").val());
var discount = parseFloat($("#discount").val());
var price = $("#price");
var total = list - (discount * list);
price.val(total.toFixed(2));
Also, if discount is in percentage (for example, say 25) then you have to divide by 100 i.e. list - (discount/100 * list)
BTW, refer this SO thread where people had warned against ToFixed usage: How to format a float in javascript?
Could do this, but what I would do instead is show the comma separated number elsewhere besides the input field.
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
$(this).val(function(index, value) {
value = value.replace(/,/g,''); // remove commas from existing input
return numberWithCommas(value); // add commas back in
});
});
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
http://jsfiddle.net/jpAmE/
I think this might do what you are looking for. Assumptions:
- Users are only allowed to enter one decimal point.
- no formatting is allowed after the decimal point, i.e. commas.
Fiddle
$('input.number').keyup(function (event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) {
event.preventDefault();
}
var currentVal = $(this).val();
var testDecimal = testDecimals(currentVal);
if (testDecimal.length > 1) {
console.log("You cannot enter more than one decimal point");
currentVal = currentVal.slice(0, -1);
}
$(this).val(replaceCommas(currentVal));
});
function testDecimals(currentVal) {
var count;
currentVal.match(/\./g) === null ? count = 0 : count = currentVal.match(/\./g);
return count;
}
function replaceCommas(yourNumber) {
var components = yourNumber.toString().split(".");
if (components.length === 1)
components[0] = yourNumber;
components[0] = components[0].replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (components.length === 2)
components[1] = components[1].replace(/\D/g, "");
return components.join(".");
}