Question

I want to show a double value to label (C#) with 2 decimal places no matters that value like 13 or 13.5 or 13.505 Its always show 13.00

Was it helpful?

Solution 2

try this method

double i=12.22222;             //first variable
double j=1.2545;              //second variable
double h=i*j;                 // multiple first and second
string s=h.ToString("0.00");  // convert to string and proper format       

this methed return

s="15.33"

OTHER TIPS

You can pass the format in to the to string method

eg:

ToString("0.00"); //2dp Number

ToString("n2"); // 2dp Number

ToString("c2"); // 2dp currency

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

To change, for example, 13.505 to 13.00 you'd also want to run it through Math.Floor or use one of the other suggested methods for rounding down.

Math.Floor(value)

http://msdn.microsoft.com/en-us/library/e0b5f0xb.aspx

If, on the other hand, you want to change 13.505 to 13.50 you'd want to run it through Math.Truncate.

Math.Truncate(Value)

http://msdn.microsoft.com/en-us/library/7d101hyf(v=vs.110).aspx

So to tie that together:

Double testValue = 13.505;
Double testValueTruncated = Math.Truncate(100 * testValue) / 100;
string withDecimalPlaces = testValueTruncated.ToString("0.00");

withDecimalPlaces will now have the value "13.50"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top