How To Convert Double To String In C#

A double is a data type used to represent floating-point numbers in programming, whereas a string is a collection of characters. When we want to show or store values as strings in programming, we frequently need to convert a double to a string.

The conversion has many advantages, including allowing us to edit the format of the output string, add currency symbols or percentage signs, and match it to regional conventions.

In this blog, we are going to look at how to change double to string in C# and a sample problem for each approach for clear understanding.

Why Do We Need To Convert Double To String In C#

Converting double to string is necessary for several reasons.

Displaying Data: We might need to display a double value in a text box, label, or other control when working with a user interface.

Data Storage: Double values might have to be stored as strings when interacting with databases or files. Because most data storage formats are designed to function with strings rather than numerical numbers.

String Manipulation: We may need to do string manipulation on a numerical number from time to time, such as concatenating it with other strings or parsing it from a larger string.

Approaches On How To Convert Double To String In C#:

There are several ways to convert double to string in C#

  1. Using Convert.ToString() Method
  2. Using the ToString() method
  3. Using ToString(IFormatProvider) Method
  4. Using the String Interpolation

A Thorough Explanation Of Each Strategy About How To Convert Double To String In C#

1. Using Convert.ToString() Method

Any numerical number or object may be quickly converted into its corresponding string representation using this built-in function from the System namespace. This technique is frequently employed when you need to quickly convert a double value to a string without considering the output’s formatting or accuracy.

Sample Code:

using System;

class Program
{
	static void Main(string[] args)
	{
    	double value = 45.1;

    	// Using Convert.ToString() method
    	string str = Convert.ToString(value);
    	Console.WriteLine("Conversion of Double to String: " + str);

    
  	 
	}
}

Output:

Conversion of Double to String: 45.1

Code Explanation:

  1. The code begins by declaring a double variable called “value” and initializing it to 45.1.
  2. After that, a string is generated from the double variable using the Convert.ToString() function.
  3.  A new string variable called “str” is created to hold the output string.
  1. Print the output string to the console.

2. Using the ToString() method

The ToString() function allows you to convert any data type to its string representation. It produces a string with a default precision of 15 digits when used with doubles. You may change this behavior by providing a format string, which controls the number of decimal places and scientific notation, as well as other formatting variables like currency symbols and date/time formats.

Sample Code:

using System;

namespace DoubleToStringExample
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double myDouble = 5.77;
        	string myStr = myDouble.ToString();

      	 
        	Console.WriteLine($"The value of myString is {myStr}");

        	Console.ReadLine();
    	}
	}
}

Output:

The value of myString is 5.77

Code Explanation:

  1. We create a static method named “Main” that acts as the program’s main entry point.
  2. Inside the Main method, we declare a new variable called “myDouble” and assign it the value 5.77.
  3. We call the ToString() method on “myDouble” and store the resulting string in a new variable called “myStr”.
  4. The value of “myStr” will be shown in the console window.

3. Using ToString(IFormatProvider) Method

The Double.ToString(IFormatProvider) function converts a double value to a string representation by using a format provider provided to control formatting. Using a specific format provider allows you to guarantee that the output is formatted in a way that is understandable by users from various cultural backgrounds, making it an excellent option for global applications.

Sample Code:

using System;
using System.Globalization;

namespace DoubleToStringExample
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double number = 99.766;
        	string str = number.ToString(new CultureInfo("en-US"));

        	Console.WriteLine($"The value of str is {str}");

    	}
	}
}

Output:

The value of str is 99.766

Code Explanation:

  1. A double variable called number is initialized with the value 99.766.
  2. The ToString method is called on the number variable with a new CultureInfo object as an argument.
  3. The CultureInfo object is created with the en-US culture, which specifies that the string representation of the number should be formatted according to the conventions of the English language in the United States.
  4. The resulting string is assigned to a variable called str.
  5. The program ends after this output is printed in the console.

4. Using the String interpolation

String interpolation in C# provides a way of converting a double to a string by inserting the value of a variable straight into a string using the $ character. The value is automatically converted into its string equivalent.

Sample Code:

using System;

namespace DoubleToStringExample
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double value = 7.88;
        	string str = $"{value}";

        	Console.WriteLine(str); 
    	}
	}
}

Output:

7.88

Code Explanation:

  1. The program first declares a double variable named value and initializes it with a value of 7.88.
  2. The double value is then changed to a string via string interpolation, which is accomplished by enclosing the variable in curly brackets within a string literal and prefixing the string literal with a $ sign.
  3. The resulting string is assigned to a string variable named str.
  4. The Console.WriteLine method is then used to output the string value to the console.

Best Of The Four Methods

For numerous reasons, ToString() method is regarded as the finest C# method to turn a double into a string.

Flexibility:  The output formatting options are very flexible when using the ToString() function.

Performance: In general, the ToString() function is faster than the other conversion techniques, especially when handling complicated situations.

Compatibility: The ToString() function is simple to employ in global applications since it is compatible with a variety of cultures and regions..

Sample Problems For Converting Double To String In C#:

Sample Problem 1:

Develop a C# application to convert Euro (EUR) to US dollars (USD) using a fixed exchange rate. Display the equivalent amount in USD as a formatted string with the currency symbol and appropriate formatting options using Convert.ToString() method.

Solution:

  1. Define the exchange rate for converting euros to US dollars.
  2. Accept the input amount in euros from the user.
  3. To determine the comparable amount in US dollars, multiply the input value by the exchange rate.
  4. Convert the calculated amount from double to string using the Convert.ToString() method.
  5. Use string formatting options, such as “${formattedAmount:N2}”, to add the currency symbol and format the amount with appropriate formatting options.
  6. Output the formatted amount string to display the equivalent amount in US Dollars with the currency symbol and formatting options.

 Code:

using System;

namespace CurrencyExchangeApp
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double amountInEUR = 1000.0; // Amount in EUR
        	double exchangeRate = 1.18; // Exchange rate for USD (1 EUR = 1.18 USD)

        	// Calculate the equivalent amount in USD
        	double amountInUSD = amountInEUR * exchangeRate;

        	// Convert double to string using Convert.ToString()
        	string formattedAmount = Convert.ToString(amountInUSD);

        	// Output the formatted amount string with currency symbol and formatting options
        	Console.WriteLine($"Equivalent Amount: ${formattedAmount:N2}");
    	}
	}
}

Output:

Equivalent Amount: $1180

Sample Problem 2:

Suppose you are building a financial application that calculates and displays the total portfolio value for an investment portfolio. The portfolio value is represented as a double value, and you need to display it as a string with a currency symbol and formatting options using ToString() method.

Solution:

  1. Declare a double variable to represent the total portfolio value.
  2. Assign a value to the double variable to represent the total portfolio value.
  3. Use the ToString() method on the double variable to convert it to a string representation.
  4. Optionally, you can provide formatting options as parameters to the ToString() method to customize the string representation, such as specifying currency symbols, the number of decimal places, etc.
  5. Store the result in a string variable.
  6. Output the formatted string representation of the total portfolio value to the console

 Code:

using System;

namespace FinancialApp
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double portfolioValue = 2534598.43;

        	// Convert double to string using ToString()
        	string formattedValue = portfolioValue.ToString();

        	// Output the formatted portfolio value
        	Console.WriteLine("Total Portfolio Value: " + formattedValue);
    	}
	}
}

Output:

Total Portfolio Value: 2534598.43

Sample Problem 3:

Consider you are developing a financial application that requires you to convert double numbers to strings in order to display currency amounts. Because the application was created to be used worldwide, it needs to be able to show quantities in various currencies and formats based on the user’s location. Write a C# program that converts double into string using ToString(IFormatProvider) method.

Solution:

  1. Declare and initialize the double value that needs to be converted to a string.
  2. Create an instance of CultureInfo to specify the culture or locale for formatting the string.
  3. Use the ToString() method with the “C” format specifier to format the double value as currency using the specified culture.
  4. Output the original double value and the formatted amount string using Console.WriteLine().
  5. Test the code with different input values, cultures, and formatting options to ensure desired currency formatting.

Code:

using System;
using System.Globalization;

namespace DoubleToStringExample
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	double value = 1567.8799;

        	// Set the culture to en-US for United States
        	CultureInfo culture = new CultureInfo("en-US");

        	// Convert double to string using ToString(IFormatProvider)
        	string formattedAmount = value.ToString("C", culture);

        	// Output the formatted amount
        	Console.WriteLine("Double Value: " + value);
        	Console.WriteLine("Formatted Amount: " + formattedAmount);
    	}
   	 
	}
}

Output:

Double Value: 1567.8799
Formatted Amount: $1,567.88

Sample Problem 4:

Imagine you are developing a sales monitoring application that uses sales data to estimate a company’s overall revenue. To display the entire revenue, which is a double value, you have to convert it into a string. You can use string interpolation to directly embed the double value into a string and display it as part of the sales report.

Solution:

  1. Declare and initialize a double variable to store the total revenue value.
  2. Use the Console.WriteLine() method to display the sales report heading.
  3. Use string interpolation with the $ symbol to directly embed the totalRevenue value as part of the sales report.
  4. Format the totalRevenue value using the N2 format specifier to display it with two decimal places and as a currency amount.
  5. Compile and run the program to see the sales report with the total revenue value displayed correctly.

 Code:

using System;

namespace SalesTrackingApp
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	// Total revenue as a double value
        	double totalRevenue = 19998775.89;

        	// Display the sales report with total revenue using string interpolation
        	Console.WriteLine("Sales Report");
    
        	Console.WriteLine($"Total Revenue: ${totalRevenue:N2}");
    	}
	}
}

Output:

Sales Report
Total Revenue: $19,998,775.89

Conclusion

In programming, converting a double to a string is a common task when we need to display, store, or modify numerical values as strings.

We examined four ways to convert a double to a string. The ToString() function is regarded as the finest among them because of its adaptability, efficiency, and usability.

However, the other approaches can be beneficial in specific situations. Understanding the approaches properly helps in determining the method that is best suited to the particular use case.