在 C# 中将字符串转换为 Double
Convert a string to Double in C#
我刚刚写了一个将字符串转换为双精度的方法。它做了它应该做的事,但它似乎太长了,我认为有更好的写法。请查看并提出更好的方法或指出为什么这对生产代码不利。
static double ConvertStringToDouble(string input, int rounding)
{
string[] split = input.Split('.');
double wholeNumber = 0.0;
if (split.Length > 0 && Int32.TryParse(split[0], out int temp))
wholeNumber = (double)temp;
double decimalNumber = 0.0;
if (split.Length > 1)
{
string decimalString = (split[1].Length < rounding) ? split[1] : split[1].Substring(0, rounding);
if (Int32.TryParse(decimalString, out int dec))
decimalNumber = (double)dec / Math.Pow(10, decimalString.Length);
}
return wholeNumber + decimalNumber;
}
这是现在更新的方法。感谢大家的贡献
static double ConvertStringToDouble(string input, int rounding)
{
if (double.TryParse(input, out double value))
return Math.Round(value, rounding);
else return 0.0;
}
.Net 为此内置了功能,称为 Double.TryParse。 Double.Parse 也存在,但建议使用 Try 变体,因为如果数字无法解析为双精度数,它不会抛出异常。你可以使用这样的方法
string stringToParse = "1.7346"
if (Double.TryParse(stringToParse, out double parsedDouble))
{
//do something with the double here
}
else
{
//failed to parse, error logic here
}
你可以只使用 double.Parse 和 double.TryParse 方法,我更喜欢这样使用它们:
string myString = "1.05";
// This throws exception:
double myParsedDouble = double.Parse(myString);
// This gives you more control over the conversion:
double? myResult = null;
if (double.TryParse(myString, out double _myResult))
myResult = _myResult;
if (myResult == null)
{
throw new ArgumentException("Not a valid double!");
}
我刚刚写了一个将字符串转换为双精度的方法。它做了它应该做的事,但它似乎太长了,我认为有更好的写法。请查看并提出更好的方法或指出为什么这对生产代码不利。
static double ConvertStringToDouble(string input, int rounding)
{
string[] split = input.Split('.');
double wholeNumber = 0.0;
if (split.Length > 0 && Int32.TryParse(split[0], out int temp))
wholeNumber = (double)temp;
double decimalNumber = 0.0;
if (split.Length > 1)
{
string decimalString = (split[1].Length < rounding) ? split[1] : split[1].Substring(0, rounding);
if (Int32.TryParse(decimalString, out int dec))
decimalNumber = (double)dec / Math.Pow(10, decimalString.Length);
}
return wholeNumber + decimalNumber;
}
这是现在更新的方法。感谢大家的贡献
static double ConvertStringToDouble(string input, int rounding)
{
if (double.TryParse(input, out double value))
return Math.Round(value, rounding);
else return 0.0;
}
.Net 为此内置了功能,称为 Double.TryParse。 Double.Parse 也存在,但建议使用 Try 变体,因为如果数字无法解析为双精度数,它不会抛出异常。你可以使用这样的方法
string stringToParse = "1.7346"
if (Double.TryParse(stringToParse, out double parsedDouble))
{
//do something with the double here
}
else
{
//failed to parse, error logic here
}
你可以只使用 double.Parse 和 double.TryParse 方法,我更喜欢这样使用它们:
string myString = "1.05";
// This throws exception:
double myParsedDouble = double.Parse(myString);
// This gives you more control over the conversion:
double? myResult = null;
if (double.TryParse(myString, out double _myResult))
myResult = _myResult;
if (myResult == null)
{
throw new ArgumentException("Not a valid double!");
}