Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to implement a thousand separator while typing in MVC 6 razor page, the code below seems to work but it shows NAN if the number is deleted completely and also shows INFINITY if a large set of numbers are also entered into the textbox, lastly, it only separates the thousand part, it doesn't add the dot and the hundredth part to it, e.g: 10000 = 10, 000, but I want it to be like this: 10000 = 10, 000.00. I appreciate any assistance.

What I have tried:

JavaScript
$(function () {
            $("#TransAmount").on('keyup', function () {
                $(this).val(numberWithCommas(parseFloat($(this).val().replace(/,/g, ""))));
            });
        });
        function numberWithCommas(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
Posted
Updated 30-Jun-23 23:12pm
v2

1 solution

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:
JavaScript
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:
JavaScript
$(".Comma").each(function(){ // To loop on each value
  var amount = parseFloat($(this).html()); // Convert string into float number
  var newamount = amount.toLocaleString('en-US'); // add comma
  $(this).html(newamount); // replace old number with new number
});

Reference 3: Use a jQuery plugin: Auto Add Thousand Separators In Numbers - Easy Number Separator | Free jQuery Plugins[^]
HTML
<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.
 
Share this answer
 
v2
Comments
Graeme_Grant 1-Jul-23 0:49am    
In some cultures, the decimal and comma are swapped
Sandeep Mewara 1-Jul-23 0:52am    
Yeah and if that is a need, hoping that Reference 2 would help. :)
Graeme_Grant 1-Jul-23 0:56am    
Also check out Japanese numbers ... separator is at 4 places, not 3.
Uwakpeter 1-Jul-23 5:45am    
Thanks, @SandeepMewara. This works for me, only that it doesn't accept decimal points, I want the numbers to be in two places of decimal.
Sandeep Mewara 1-Jul-23 7:47am    
Glad to know it worked for you.

You can again have custom logic to floor the number to 2 digits before merging back. It's in your control if you want to limit to two places only.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900