1

I have a serial number which is String type.

Like This;

String.Format("{0:####-####-####-####}", "1234567891234567" );

I need to see Like This, 1234-5678-9123-4567;

Bu this Code does not work?

Can you help me?

4
  • And I tried this, String.Format("{0:####-####-####-####}", Double.Parse("1234567891234567") ); But I see like this 1234-5678-9123-4568 why? Double.Parse increase last digit. I dont understand. Commented Sep 29, 2009 at 10:22
  • That's an other problem all together. Check stackoverflow.com/questions/1193630/… Commented Sep 29, 2009 at 10:23
  • Double.Parse("1234567891234567") will result in a rounding error, since a Double can't hold that many digits. An Int64 can! Commented Sep 29, 2009 at 10:25
  • Does your serial number contain only digits or can it contain non-digit characters too? Commented Sep 29, 2009 at 10:27

2 Answers 2

3

That syntax takes an int, try this:

String.Format("{0:####-####-####-####}", 1234567891234567);

Edit: If you want to use this syntax on a string try this:

String.Format("{0:####-####-####-####}", Convert.ToInt64("1234567891234567"))
Sign up to request clarification or add additional context in comments.

2 Comments

No I can not do this; String mycode= "1234567891234567"; String.Format("{0:####-####-####-####}", mycode); I use diynamic serial number. So I use String variable.
Seems a bit convoluted to convert the string to a long only to convert it back to a string again.
2

For ####-####-####-####, you will need a number. But you're feeding it a string.

It would be more practical to pad the string with additional zero's on the left so it becomes exactly 16 characters. Then insert the dash in three locations inside the string. Converting it to an Int64 will also work but if these strings become bigger or start to contain non-numerics, then you will have a problem.

string Key = "123456789012345";
string FormattedKey = Key.PadLeft(16, '0').Insert(12, "-").Insert(8, "-").Insert(4, "-");

That should be an alternative to formatting. It makes the key exactly 16 characters, then inserts three dashes from right to left. (Easier to keep track of indices.)

There are probably plenty of other alternatives but this one works just fine.

3 Comments

So How Can I Format a string variable?
To use the syntax you tried above, convert the string to an int
Or use the alternate solution that I've added to my answer. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.