Stack Overflow Asked by Viking on December 27, 2021
I am adding a comma to thousand number but those numbers have decimal value so that decimal value also added comma which I don’t want
Eg: default number 2476.570550272 and I want to add comma 2,476.570550272
After using the below code I am getting comma to decimal number also like this 2,476.570,550,272.
$.fn.digits = function () {
return this.each(function () {
$(this).text($(this).text().replace(/(d)(?=(ddd)+(?!d))/g, "$1,"));
})
}
$(".number").digits();
Try with this.
function numberWithCommas(ADD-YOUR-NUM-HERE) {
var parts = number.toString().split(".");
parts[0] = parts[0].replace(/B(?=(d{3})+(?!d))/g, ",");
return parts.join(".");
}
Answered by Krupal Panchal on December 27, 2021
Here's a vanilla-flavored adaptation of your regex that works as you specified.
digits(document.querySelectorAll(".numInput"));
function digits(inputs){
for(let input of inputs){
const [int, dec] = input.value.split(".");
input.value = int.replace(/(d)(?=(ddd)+(?!d))/g, "$1,") + (dec ? "."+dec : "");
}
}
<input class="numInput" value="4321.09876" />
<input class="numInput" value="987654321" />
<input class="numInput" value=".123456789" />
Answered by Cat on December 27, 2021
Javascript has a function for this, it's called NumberFormat:
const number = 123456.789123123123;
const yourFormat = new Intl.NumberFormat('en-EN',{ maximumFractionDigits: 5 });
console.log(yourFormat.format(number));
The function is very versatile, here you can find more options. I suggest a read for what it can do for future usage also. It has many options and is also very recommendable for currencies.
Answered by Martijn on December 27, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP