FiveTools
FiveTools

Reputation: 6030

using string format for a credit card number

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?

Upvotes: 6

Views: 16949

Answers (5)

Srishu Indrakanti
Srishu Indrakanti

Reputation: 1

probably easier to write your own function

getFormattedCardNumber(String cardNumber) {
    String formatted="";
    var chars=cardNumber.characters;
    for(int i=0;i<chars.length;i++) {
      if(i!=0 && i%4==0) formatted+="-";
      formatted+=chars.elementAt(i);
    }
    return formatted;
}

Upvotes: 0

Maury
Maury

Reputation: 604

ccNumber can be string

Regex.Replace(ccNumber, @"(\w{4})(\w{4})(\w{4})(\w{4})", @"$1 $2 $3 $4");

Upvotes: 1

dcarneiro
dcarneiro

Reputation: 7190

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")))

Upvotes: 13

bartosz.lipinski
bartosz.lipinski

Reputation: 2677

ccNumber.ToString("#### #### #### ####")

Upvotes: 1

Mitja Bonca
Mitja Bonca

Reputation: 4546

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);

Upvotes: 1

Related Questions