Insert Commas Into A String Variable using C#

This post describes the C Sharp code I use to insert commas into string variables representing a numerical amount that may be at least one thousand or greater. It is useful for application development that includes sales and accounting reports, check writing, order entry/invoicing, quoting, job costing and more.

The code below shows how I orchestrate this function:

  1. amount_variable_string = new string(amount_variable);  
  2. if (numerical_amount >= 100000 && numerical_amount < 100000000 && amount_variable_string.Substring(3, 1) != " ")  
  3. {  
  4.     amount_variable_string = amount_variable_string.Substring(0, 4) + "," + amount_variable_string.Substring(4, 6);  
  5. }  
  6. if (numerical_amount >= 100000000 && amount_variable_string.Substring(0, 1) != " ")  
  7. {  
  8.     amount_variable_string = amount_variable_string.Substring(0, 1) + "," + amount_variable_string.Substring(1, 3) + "," + amount_variable_string.Substring(4, 6);  
  9. }  
  10. if (numerical_amount < 100000)  
  11. {  
  12.     amount_variable_string = " " + amount_variable_string;  
  13. }  
numerical_amount” is a long integer variable that contains the numerical value. “amount_variable” is a character array that contains the character equivalent of the amount in “numerical_amount”. “amount_variable_string” is the string variable equivalent of “amount_variable”.

The character array, “amount_variable”, is 10 characters in size with the two rightmost digits representing the “cents” to the right of the decimal point. Please keep this in mind when I narrate what the above code does.

First, if the numerical value is greater than or equal to 1,000 and less than 1,000,000 and the third character from the left of its string expression isn’t a space character, then concatenate the first four characters of the string expression to a comma and then to the last six characters of the string expression.

Next, if the numerical value is greater than or equal to 1,000,000 and the first character from the left of its string expression isn’t a space character, then concatenate the first character of the string expression to a comma and then to the next three characters of the string expression and then to another comma and then to the last six characters of the string expression. Lastly, if the numerical amount is less than 1,000, then concatenate a space character to the beginning of the string variable.

Most coders can see this is a fairly simple way to apply a format mask to a variable containing a numerical amount. Using my way, you will need both the numerical and string expressions for the same amount you intend to format. There may be a more compact way to do the same thing, but this seems to work well enough for me.