简体   繁体   English

变量将小数转换为整数

[英]Variable Conversion decimal to int

If I explicitly convert a decimal value to an integer value, will the decimal values simply be truncated or will the value be rounded off? 如果我将十进制值明确转换为整数值,那么十进制值会被截断还是四舍五入?

for example: if d = 8.89 例如:如果d = 8.89

int i = (int)d;

Will i be 8 or 9 ?? i会是8岁还是9岁?

It will truncate to 8. 它将截断为8。

If you would like it to round, you can use something like: 如果您想四舍五入,可以使用以下方法:

int i = (int)Math.round(d);

From the C# Language Specification V5 1 §6.2.1 Explicit numeric conversions : 从C#语言规范V5 1§6.2.1 显式数字转换

For a conversion from decimal to an integral type, the source value is rounded towards zero to the nearest integral value, and this integral value becomes the result of the conversion. 对于从十进制到整数类型的转换,源值朝零舍入到最接近的整数值,并且该整数值成为转换的结果。 If the resulting integral value is outside the range of the destination type, a System.OverflowException is thrown. 如果结果积分值超出目标类型的范围,则抛出System.OverflowException。

Other languages/platforms which have a type like decimal may have different rules: in each and every case you need to check the rules specific to that language/platform. decimal类型的其他语言/平台可能具有不同的规则:在每种情况下,您都需要检查特定于该语言/平台的规则。 Eg. 例如。 rules for T/SQL are different : T / SQL的规则不同

By default, SQL Server uses rounding when converting a number to a decimal or numeric value with a lower precision and scale. 默认情况下,SQL Server在将数字转换为精度和小数位数较低的十进制或数字值时使用舍入。 However, if the SET ARITHABORT option is ON, SQL Server raises an error when overflow occurs. 但是,如果SET ARITHABORT选项为ON,则在发生溢出时SQL Server会引发错误。 Loss of only precision and scale is not sufficient to raise an error. 仅精度和规模的损失不足以引起误差。


1 As included with Visual Studio 2013. 1与Visual Studio 2013一起提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM