c# - Convert.ToInt32 行为字符串与 float / double 文字

标签 c# type-conversion

Convert.ToInt32 在传递 stringfloat/double literal

时表现不同
var result = Convert.ToInt32(12.4);//returns 12
result = Convert.ToInt32(12.44);//returns 12
result = Convert.ToInt32(12.4444444);//returns 12       
result = Convert.ToInt32("12.4"); // Input string was not in a correct format.

我了解 Convert.ToInt32 的不同重载正在为 string 调用和 float/double

问题是为什么这种不一致的行为不应该 singleConvert.ToInt32 重载而抛出精度丢失的异常?

最佳答案

The question is why this inconsistent behavior shouldn't single overload for Convert.ToInt32 throw an exception for loss of precision ?

您可以将当前用于将 double 转换为 int 的实用方法视为 “转换” (int)12.4, (int)12.44 等,这在本质上意味着你肯定知道你很可能会失去数据精度,因此简而言之就像告诉编译器 “继续转换它,因为我不介意数据丢失”,因此,不会抛出异常,而最后一个例子是从 string 转换为 int 应该 抛出异常,因为根据 MSDN:

ToInt32(String) method is equivalent to passing value to the Int32.Parse(String).

众所周知,如果指定的字符串格式不正确,Int32.Parse(String) 会抛出异常。

关于c# - Convert.ToInt32 行为字符串与 float / double 文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140482/

相关文章:

php - 将 Wordpress Longtext 值转换为有效日期

c++ - 私有(private)转换函数导致 "ambiguous default type conversion"错误 (c++)

ios - NSString 的值是 iOS 中的 NSInteger 值吗

c# - 从 C# 程序中反序列化 JSON 时,我是否需要使用 JavaScriptSerializer 以外的任何东西?

c# - 在 Roslyn 的哪个位置,作为 IL 发出的 C# 'class' 语句?

c# progressbar 不更新

javascript - 使用javascript将音频文件转换为base64

c# - 部分类文件名的命名约定?

c# - 排除正则表达式组值

c# - 在大型数据集的可枚举 LINQ 查询结果上使用 ToList() - 效率问题?