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("#### #### #### ####")
Share:
14,151
FiveTools
Author by

FiveTools

Updated on June 15, 2022

Comments

  • FiveTools
    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
    FiveTools about 13 years
    I expect the string to have a space after four digits - 1234 5678 9123 4567 - and it looks like 1234567891234567.
  • dcarneiro
    dcarneiro about 13 years
    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")))
  • FiveTools
    FiveTools about 13 years
    Make sure the number is not already in string format! once I converted to long, it worked as expected.
  • Chris Marisic
    Chris Marisic about 13 years
    Major issue with using this though is all leading and trailing 0s will be destroyed.
  • dcarneiro
    dcarneiro about 13 years
    @Chris Marisic String.Format only cuts leading and trailing zeros if you format with #### instead of 0000.
  • Chris Marisic
    Chris Marisic about 13 years
    Arguably 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
    live-love over 12 years
    That doesn't work for 20 digit credit cards (Int64.Parse overflow)