printf and format in c#

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Hi, how would I translate this to c#?

char ttext[100];
sprintf(ttext,"%2.2i %-.10s %8.3f",1,"Mark",123.24);

[expected output] 01 Mark<6spaces> 123.240

Thanks
 
Hi Mark,

Thank you for posting in the community! My name is Jeffrey, and I will be
assisting you on this issue.

Based on my understanding, you want to format numeric in string in C#.
================================================
First, I want to remind you that sprintf(ttext,"%2.2i %-.10s
%8.3f",1,"Mark",123.24) will output:
"01 Mark<0spaces> 123.240" instead of "01 Mark<6spaces> 123.240"

If you want to get your expected output, you should use:
sprintf(ttext,"%2.2i %-10.10s %8.3f",1,"Mark",123.24);

In C#, you can use String.Format method to format numeric into string.
You can try the following Solution to see if it helps resolve your issue:

string result=String.Format("{0,2:00} {1,-10} {2, 8: #.000}",1,"Mark",
123.24);
Console.WriteLine(result);

It will output your wanted string: "01 Mark<6spaces> 123.240"

String.Format method takes one format parameter which is in the form:
{index[,alignment][:formatString]} .
For more information of each fields, please refer to:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemstringclassformattopic1.asp

Also, you can find "Standard Numeric Format Strings" and "Custom Numeric
Format Strings" documents in:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpconstandardnumericformatstrings.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpconcustomnumericformatstrings.asp

There are also samples in:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpconstandardnumericformatstringsoutputexample.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpconcustomnumericformatstringsoutputexample.asp

================================================
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.
Have a nice day!!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top