You are hereFormat Numbers With Thousand Separators on a .NET page
Format Numbers With Thousand Separators on a .NET page
This will show you how to display and edit numbers with thousand separators on .NET page.
Display
Displaying numbers with thousand separators is easy. You could use the following C# function to format a text box value :
public string formatSeparators(string val)
{
if(val != string.Empty){
long dValue = Convert.ToInt32(val);
return String.Format ("{0:#,0}", dValue);
}
else
return string.Empty;
}
Editing
Now, editing is a bit more difficult. We need to use JavaScript on the client to help us format numbers.
First, attach the following code on Page Load:
txtId.Attributes.Add("onblur", "formatNumber(this)");
The onblur event occurs every time the user leaves an input field, and the JavaScript function is executed.
Here is a listing for the JavaScript formatNumber function:
function formatNumber(obj){
var str = obj.value;
//remove non-digits
var reg1 = /[^\d]/g;
str = str.replace(reg1,"");
//insert thousand separators
var reg2=/(-?\d+)(\d{3})/;
while(reg2.test(str)){
str=str.replace(reg2,'$1,$2')
}
obj.value= str;
}
This code allows you to edit and display separators on the page. But that's not all. We also need to save numbers on the server, probably to a database.
Saving
To save a formatted value, we need to strip off separators. The following piece of code does it:
public int convertField(string str)
{
return Int32.Parse(str,System.Globalization.NumberStyles.AllowThousands);
}
That is the basic technique that shows how to display and edit numbers with thousand separators in .NET. Of course, you would need to perform extra validation and read from and save to a database but that is outside the scope of this article.