One of the ways could be to:
1. separate the decimal part
2. regex the integer part
3. put decimal and integer parts back together
Have a look at few examples here:
Reference 1 (Javascript based):
JavaScript Number Format - Add Commas - mredkj.com[
^]
Example 1:
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;
}
Results:
addCommas(1000)
// 1,000
addCommas(1231.897243)
// 1,231.897243
addCommas('9999999.00')
// 9,999,999.00
addCommas(-500000.99)
// -500,000.99
In case you are looking more locale/region specific, then you can simply use:
toLocaleString()
Reference 2:
Number.prototype.toLocaleString() - JavaScript | MDN[
^]
Example:
$(".Comma").each(function(){
var amount = parseFloat($(this).html());
var newamount = amount.toLocaleString('en-US');
$(this).html(newamount);
});
Reference 3: Use a jQuery plugin:
Auto Add Thousand Separators In Numbers - Easy Number Separator | Free jQuery Plugins[
^]
<script src="easy-number-separator.js"></script>
<input type="text" class="number-separator" placeholder="Enter Your Number Here...">
For handling
NaN
, you need to first check if it's a valid value to convert to a float or not.
You can make use of
isNaN()[
^] and accordingly handle the desired value.
For handling
Infinity
, you need to be within the limits datatype supports.
Quote:
Infinity values are returned when the number is outside the double-precision 64-bit IEEE 754-2019 format range
Reference:
parseFloat() - JavaScript | MDN[
^]
One possible way to handle very large value is to find alternate datatype like
bigint[
^] or so. Nothing standard that I know of.
Try and adjust to you need.