How to

format numbers

Published: 14. January 2009 | Updated: 26. October 2011
License: Microsoft Public License (MS-PL)
Categories: Framework » Strings
Tags: C# Formatting Text
Was this snippet helpful for you? YESYES / NONO

Quick sample how to format numbers in .NET. Find more info on http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx.
double myDouble = 193.8701;
int myInt = 350;

// currency
Console.WriteLine(myDouble.ToString("C"));

// decimal (supports only integral types)
Console.WriteLine(myInt.ToString("D"));

// scientific (exponential)
Console.WriteLine(myDouble.ToString("E"));

// fixed-point
Console.WriteLine(myDouble.ToString("F"));

// general
Console.WriteLine(myDouble.ToString("G"));

// number
Console.WriteLine(myDouble.ToString("N"));

// percent
Console.WriteLine(myDouble.ToString("P"));

// round-trip
Console.WriteLine(myDouble.ToString("R"));

// hexadecimal  (supports only integral types)
Console.WriteLine(myInt.ToString("X"));
Console Output:
$193.87
350
1.938701E+002
193.87
193.8701
193.87
19,387.01 %
193.8701
15E
Send us feedback about this snippet »



Related Snippets: