Groups | Blog | Home
all groups > vj# > february 2005 >

vj# : Controlling number of decimal places


Lou
2/24/2005 9:21:01 AM
I have a double value 1.2344567

I want to convert to a String with just two decimal places (always showing
two places even if zeroes).

Any suggestions? (I know how to do it in Java using DecimalFormat class, but
atw13
2/24/2005 9:05:05 PM
System.Decimal d = new System.Decimal(yourfloat);
String s = d.ToString("C");

The easiest way I see to do it is the above. Create a System.Decimal object
from your float, and then use the "c" argument in the toString method of
Lars-Inge Tønnessen [VJ# MVP]
2/25/2005 9:48:46 PM

Please use System.String.Format( "{0:#.00}", System.Convert.ToDecimal(
value ) ) to format the number of digits.

{0 = the parameter index. We only have 1 parameter so this will always be 0.
# = the value, it does not matter how many digits.
0 = represents a digit.



Example:

//double value = 1.2344567;
double value = 111.2;

String s_value = System.String.Format( "{0:#.00}",
System.Convert.ToDecimal( value ) );

System.Console.WriteLine( "The value is: " + s_value );


output:
The value is: 111.20


Eg
String s_value = System.String.Format( "{0:#.000}",
System.Convert.ToDecimal( value ) );

Will give:
The value is: 111.200



Regards,
Lars-Inge Tønnessen

AddThis Social Bookmark Button