Using ToString() Method:
The ToString()
method is available on all objects in C# and provides a string representation of the object.
double myDouble = 42.567;
string myString = myDouble.ToString();
Console.WriteLine("Converted String: " + myString);
Output:
Converted String: 42.567
In this example, the ToString()
method is called on the myDouble
variable, resulting in a string representation of the double value.
String.Format() Method:
Another way to convert doubles to strings is by using the String.Format()
method. This method allows for more control over the format of the resulting string.
double myDouble = 1234.5678;
string myString = string.Format("{0:F2}", myDouble);
Console.WriteLine("Formatted String: " + myString);
Output:
Formatted String: 1234.57
Here, the format specifier "{0:F2}"
ensures that the double value is formatted with two decimal places.
Interpolation and Concatenation:
C# also supports string interpolation and concatenation for converting doubles to strings.
double myDouble = 9876.54321;
string myStringInterpolated = $"{myDouble:F3}";
string myStringConcatenated = "Value: " + myDouble;
Console.WriteLine("Interpolated String: " + myStringInterpolated);
Console.WriteLine("Concatenated String: " + myStringConcatenated);
Output:
Interpolated String: 9876.543
Concatenated String: Value: 9876.54321
In the above example, the $"{myDouble:F3}"
syntax in the interpolated string ensures three decimal places.
Comments (0)