📅  最后修改于: 2023-12-03 14:59:39.943000             🧑  作者: Mango
When working with double precision floating point numbers in C#, it is sometimes required to convert them to string format with a dot as decimal separator. This can easily be done using the ToString
method with a specified culture that uses the dot as decimal separator.
double number = 3.14159;
string strNumber = number.ToString(CultureInfo.InvariantCulture);
Console.WriteLine(strNumber); // output: "3.14159"
In the code above, we first declare a double precision floating point number with a value of 3.14159. We then use the ToString
method to convert this number to a string using the CultureInfo.InvariantCulture
culture, which is a culture that uses the dot as decimal separator. Finally, we print out the resulting string to the console.
It's worth noting that if we were to use the default culture, which is determined by the system settings, we might get a different decimal separator, depending on the regional settings of the computer. For example, in some locales the comma "," is used as a decimal separator instead of the dot ".". Therefore, it's important to always specify the culture when converting numbers to strings to avoid unexpected behavior and errors.
Here's an example of using the default culture:
double number = 3.14159;
string strNumber = number.ToString();
Console.WriteLine(strNumber); // output: "3,14159" (if the default culture uses comma as decimal separator)
As you can see, we did not specify the culture in this example, so the result depends on the default culture of the computer.
In summary, when converting double precision floating point numbers to string with a dot as decimal separator in C#, we should always specify the CultureInfo.InvariantCulture
culture to get the expected result, regardless of the regional settings of the computer.