fredag 14 mars 2008

Decimal type; howto control the decimal output

Formatting a decimal value to display only the applicable number of decimals might not seem to be an easy thing if you are using only the "ToString" method.

Example:
decimal d1 = decimal.Parse("100.510");
decimal d2 = decimal.Parse("100.00");
decimal d3 = decimal.Parse("100.50");


Lets say you want to output the value just with its applicable number of decimals, ie #1 = 2 decimals, #2 = 0 decimals and #3 = 1 decimal.

To do this, you definitely do not need to use any string formatting or such, instead simply use the ToString method with the the following format: "G29".
The solution is really simple and has been around since .NET 1.0.

Example:
d1.ToString("G29"); //100.51
d2.ToString("G29"); //100
d3.ToString("G29"); //100.5

Inga kommentarer: