using string format for a credit card number
14,151
Solution 1
String.Format("{0:0000 0000 0000 0000}", number)
EDIT
I paste my comment here to made it readable:
ccNumber is an Int or a string? if it's an int it should work. if it's a string you need to do a
String.Format("{0:0000 0000 0000 0000}", (Int64.Parse("1234567812345678")))
Solution 2
You better you a masked textBox, and set the mask to:
this.maskedTextBox1.Mask = "0000 0000 0000 0000";
or set the string format to:
long number = 1234123412341234;
textBox1.Text = String.Format("{0:0000 0000 0000 0000}", number);
Solution 3
ccNumber.ToString("#### #### #### ####")
Author by
FiveTools
Updated on June 15, 2022Comments
-
FiveTools almost 2 years
I'm trying to display a credit card number as a string like #### #### #### ####
I tried:
txtbox.Text = string.Format("{0:#### #### #### ####}", ccNumber);
and it didn't work. Any ideas?
-
FiveTools about 13 yearsI expect the string to have a space after four digits - 1234 5678 9123 4567 - and it looks like 1234567891234567.
-
dcarneiro about 13 yearsccNumber is an Int or a string? if it's an int it should work, if it's a string you need to do a String.Format("{0:0000 0000 0000 0000}", (Int64.Parse("1234567812345678")))
-
FiveTools about 13 yearsMake sure the number is not already in string format! once I converted to long, it worked as expected.
-
Chris Marisic about 13 yearsMajor issue with using this though is all leading and trailing 0s will be destroyed.
-
dcarneiro about 13 years@Chris Marisic String.Format only cuts leading and trailing zeros if you format with #### instead of 0000.
-
Chris Marisic about 13 yearsArguably
String.Format("{0:0000 0000 0000 0000}", number)
is even more nefarious since that will turn a 15 digit CC into a 16 digit CC etc. -
live-love over 12 yearsThat doesn't work for 20 digit credit cards (Int64.Parse overflow)