c# - c# 中的转换错误抛出异常输入字符串格式无效

标签 c#

<分区>

我在将字符串转换为十进制时遇到问题。我的 C# 代码正在从 exel 文件中读取以下数据并向我抛出以下错误

Input string was not in the correct format "-1.7999999999999999E-2".

我在我的 excel 值中看不到这个值。

示例数据

-1.70152
9.335628333
-150.0145233
39.159625

c#代码

TestModel.lat = Convert.ToDecimal(c.CellValue.Text);

我的转换是否正确。我在转换过程中丢失了任何值。为了保留原始值,最好转换成什么数据类型?

最佳答案

您的方法必须是:

TestModel.lat = Decimal.Parse(c.CellValue.Text, NumberStyles.Float);

更好的是你应该使用 Decimal.TryParse 并且你应该指定 InvariantCulture

decimal d = 0;
Decimal.TryParse("1.2345E-02", System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture, out d);

TestModel.lat = d;

关于c# - c# 中的转换错误抛出异常输入字符串格式无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097490/

相关文章:

c# - 如何处理 NULLS : C#, Microsoft SDS 1.3 和 NetCDF 文件

c# - 使用 == 比较两个结构

c# - ObjectContext.Translate - 使用不同的属性名称

c# - 服务模式 Entity Framework asp.net mvc

C#、objectCollection.OfType<T>() 和 foreach(objectCollection 中的 T 项)、IEnumerable 到 IEnumerable<T>

c# - 使用 int 作为除数时计算公式的最佳方法是什么

c# - 程序占用太多内存

C# ffmpeg 无法加载 dll avcodec

C# => 在这种特殊情况下,带有参数的 Lambda 表达式似乎过于流畅/毫无意义

c# - Windows Phone 8 连接检查 WebClient 抛出可怕的 System.Net.WebException