Relationship with ToString() C# with Example



Relationship with ToString() C# with Example

While the String.Format() method is certainly useful in formatting data as strings, it may often be a bit overkill, 
especially when dealing with a single object as seen below : 
String.Format("{0:C}", money); // yields "$42.00" 
An easier approach might be to simply use the ToString() method available on all objects within C#. It supports all 
of the same standard and custom formatting strings, but doesn't require the necessary parameter mapping as 
there will only be a single argument : 
money.ToString("C"); // yields "$42.00" 
Caveats & Formatting Restrictions 
While this approach may be simpler in some scenarios, the ToString() approach is limited with regards to adding 
left or right padding like you might do within the String.Format() method : 
$42.00" 
String.Format("{0,10:C}", money); // yields " 
In order to accomplish this same behavior with the ToString() method, you would need to use another method 
like PadLeft() or PadRight() respectively : 
money.ToString("C").PadLeft(10); // yields " $42.00" 
 

0 Comment's

Comment Form

Submit Comment