Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number to String (Always 2 decimal Place) [closed]

Tags:

c#

format

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

like image 333
Bharat Jangir Avatar asked Apr 29 '14 10:04

Bharat Jangir


People also ask

How do I format a string to two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I restrict float upto 2 decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

What is the number 2.738 correct to 2 decimal places?

74, which is 2 decimal places.


2 Answers

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"

like image 150
Murphy Avatar answered Oct 02 '22 18:10

Murphy


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"
like image 28
Manoj Avatar answered Oct 02 '22 20:10

Manoj