Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to append some characters in start of an integer string. for eg my string is "45"
I want to append fourteen 0 before it like 0000000000000045.
The problem is,my string's length may vary, it can be of 4 characters, sometimes 3 or more then 10 characters.
I just want to make it 16 characters string,by appending 0 before it.
how can I do this?

What I have tried:

I am doing this
(my_string).PadLeft(16 , '0');


but it will fail if length is more then 10
Posted
Updated 4-Jul-17 3:12am
Comments
Richard Deeming 4-Jul-17 8:36am    
PadLeft works fine for me. If the string length is less than 16, it prepends enough 0's to make it exactly 16 characters. If the string length is greater than or equal to 16, it returns the string unchanged.

NB: PadLeft returns the modified string. It does not modify the original string. If you're not storing or using the returned value anywhere, you won't see the result.
Syed Salman Raza Zaidi 5-Jul-17 0:37am    
I am storing it in a new string

In addition to PadLeft, it's worth keeping it as an integer number, and using ToString to "pad" it to the "full length" only when you want to present it to the user:
C#
int i = 45;
string padded = i.ToString("D16");
 
Share this answer
 
e.g. number is an int of 45
and you want to have a string which is 16 characters long.

var number = 45;
var text = number.ToString("D16");


Please have a look at this
Standard Numeric Format Strings | Microsoft Docs[^]
 
Share this answer
 
v4
Comments
Richard Deeming 4-Jul-17 9:18am    
16 characters, not 16 bytes! :)
TheRealSteveJudge 4-Jul-17 9:22am    
You're right. Thank you.

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