c#中string转为float
时间: 2023-08-04 18:09:32 浏览: 123
在 C# 中将字符串转换为浮点数可以使用 `float.Parse()` 方法或 `float.TryParse()` 方法。
`float.Parse()` 方法将字符串解析为浮点数,如果字符串无法解析为浮点数,则会引发 `FormatException` 异常。示例代码如下:
```csharp
string str = "3.14";
float f = float.Parse(str);
Console.WriteLine(f); // 输出 3.14
```
`float.TryParse()` 方法尝试将字符串解析为浮点数,如果解析成功,则返回 `true`,并将解析结果存储在指定的输出参数中;如果解析失败,则返回 `false`,并将输出参数设置为 0。示例代码如下:
```csharp
string str = "3.14";
float f;
if (float.TryParse(str, out f))
{
Console.WriteLine(f); // 输出 3.14
}
else
{
Console.WriteLine("无法解析为浮点数");
}
```
同时,还可以指定解析时使用的文化(Culture),例如:
```csharp
string str = "3,14";
float f = float.Parse(str, new CultureInfo("fr-FR"));
Console.WriteLine(f); // 输出 3.14
```
上述代码将使用法语(法国)文化来解析字符串,因此使用的是逗号作为小数点分隔符。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)