Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surprising int.ToString output

Tags:

I have been working on a project, and found an interesting problem:

2.ToString("TE"+"000"); // output = TE000
2.ToString("TR"+"000"); // output = TR002

I also have tried with several strings other than "TE" but all have the same correct output.

Out of curiosity, I am wondering how come this could have happened?

like image 230
Manto Tan Avatar asked Dec 06 '14 21:12

Manto Tan


1 Answers

Simply based on Microsoft's documentation, Custom Numeric Format Strings, your strings "TE000" and "TR000" are both custom format strings, but clearly they are parsed differently.

2.ToString("TE000") is just a bug in the formatter; it's going down a buggy path because of the unescaped "E". So it's unexpectedly assuming the whole thing is a literal.

2.ToString("TR000") is being interpreted as an implied "TR" literal plus 3 zero-filled digits for an integer value; therefore, you get "TR002".

If you truly want TE and TR verbatim, the expressions 2.ToString("\"TE\"000") and 2.ToString("\"TR\"000") will accomplish that for you by specifying TE and TR as explicit literals, instead of letting the formatter guess if they are valid format specifiers (and getting it wrong).

like image 153
Suncat2000 Avatar answered Oct 15 '22 21:10

Suncat2000