Pages

How to Remove Leading Zeros from a String in C#

If you have a string representing a number with leading zeros, such as "0045," and want to convert it to "45," you can parse it into an integer and then convert it back to a string.

Method 1: Using int.Parse()


  string input = "0045";
  int number = int.Parse(input); // Converts "0045" to 45 (integer)
  string output = number.ToString(); // Converts it back to "45" (string)
  Console.WriteLine(output); // Output: 45  

Method 2: Using Convert.ToInt32()

Another way to remove leading zeros is by using Convert.ToInt32(), which works similarly to int.Parse() but handles null values more gracefully:

  string input = "0045";
  int number = Convert.ToInt32(input); // Converts "0045" to 45 (integer)
  string output = number.ToString(); // Converts it back to "45" (string)
  Console.WriteLine(output); // Output: 45
  
This approach ensures that your data is correctly formatted based on your needs. Happy coding! 🚀

References

Microsoft. (n.d.). Int32.Parse Method. Microsoft Docs. Retrieved from https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse
Microsoft. (n.d.). Convert.ToInt32 Method. Microsoft Docs. Retrieved from https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32

No comments:

Post a Comment