将字符串转换为浮点数的正确方法


大家好,
愚蠢的问题,但我需要将从文件中读取的字符串转换为浮点数,即“0.45”到0.45。 我过去使用的一种方法是做

string strValue = "0.45";
fltValue = strValue.ToDouble();

这给出了一个我似乎记得的浮点数,但它很大。
有没有简单、快速的方法来获取两位数?
我见过 ConvertTo.Decimal() 和 ConvertTo.Double(),只是想做得正确!

我尝试过的:

Uncle Google,MSDN Docs,添加 ToDouble() 和 ConvertTo 并尝试使用 C 方法转换值

Max_Value = (float)StrMax_Value;

解决方案1

引用:

这给出了一个我似乎记得的浮点数,但它很大。

你用“BIG”来表达什么意思?
你知道, double 数据大小是 8 字节(与您使用的转换方法无关)。

出了什么问题 Double.Parse 方法(系统)| 微软学习[^] 和 Double.TryParse 方法(系统)| 微软学习[^]?

解决方案2

我相信正确的方法是这样的

C#
string strValue= "0.45"; 

if (string.IsNullOrEmpty(strValue))
{
  // Handle the case of null or empty string (e.g., return default value, throw exception)
  Console.WriteLine("String is null or empty.");
  return; // Or throw an exception
}

// Proceed with conversion only if the string is not null or empty
float floatValue;

if (!float.TryParse(strValue, out floatValue))
{
  // Handle the case of invalid format or raise Exception
  Console.WriteLine("Invalid number format.");
}

//Conversion successful, use floatValue

理想情况下,您应该有一个具有 Helper 函数(例如 ConvertToFloat)的 Helper 类,您可以在其中嵌入上述逻辑以获得一致的输出。

コメント

タイトルとURLをコピーしました