如何在 C# 中将小数转换为 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/501090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:49:00  来源:igfitidea点击:

How do I convert a decimal to an int in C#?

c#.netintdecimal

提问by

How do I convert a decimal to an int?

如何将十进制转换为整数?

回答by jason

Use Convert.ToInt32from mscorlibas in

使用Convert.ToInt32from mscorlibas in

decimal value = 3.14m;
int n = Convert.ToInt32(value);

See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in

请参阅MSDN。您也可以使用Decimal.ToInt32. 再次,请参阅MSDN。最后,您可以像这样进行直接转换

decimal value = 3.14m;
int n = (int) value;

which uses the explicit cast operator. See MSDN.

它使用显式转换运算符。请参阅MSDN

回答by Andy

System.Decimalimplements the IConvertableinterface, which has a ToInt32()member.

System.Decimal实现IConvertable接口,它有一个ToInt32()成员。

Does calling System.Decimal.ToInt32()work for you?

打电话System.Decimal.ToInt32()对你有用吗?

回答by luiscubal

decimal d = 2;
int i = (int) d;

This should work just fine.

这应该工作得很好。

回答by ICR

int i = (int)d;

will give you the number rounded down.

会给你四舍五入的数字。

If you want to round to the nearest even number (i.e. >.5 will round up) you can use

如果您想四舍五入到最接近的偶数(即 >.5 将四舍五入),您可以使用

int i = (int)Math.Round(d, MidpointRounding.ToEven);

In general you can cast between all the numerical types in C#. If there is no information that will be lost during the cast you can do it implicitly:

通常,您可以在 C# 中的所有数字类型之间进行转换。如果在转换过程中没有信息会丢失,您可以隐式地进行:

int i = 10;
decimal d = i;

though you can still do it explicitly if you wish:

如果你愿意,你仍然可以明确地做到这一点:

int i = 10;
decimal d = (decimal)i;

However, if you are going to be losing information through the cast you must do it explicitly (to show you are aware you may be losing information):

但是,如果您要通过演员表丢失信息,则必须明确地这样做(以表明您知道您可能会丢失信息):

decimal d = 10.5M;
int i = (int)d;

Here you are losing the ".5". This may be fine, but you must be explicit about it and make an explicit cast to show you know you may be losing the information.

在这里你失去了“.5”。这可能没问题,但是您必须明确说明并进行明确的转换以表明您知道您可能会丢失信息。

回答by DeadlyBrad42

A neat trick for fast rounding is to add .5 before you cast your decimal to an int.

快速舍入的一个巧妙技巧是在将小数转换为 int 之前加上 0.5。

decimal d = 10.1m;
d += .5m;
int i = (int)d;

Still leaves i=10, but

还是离开了i=10,但是

decimal d = 10.5m;
d += .5m;
int i = (int)d;

Would round up so that i=11.

将四舍五入这样i=11

回答by DeadlyBrad42

You can't.

你不能。

Well, of course you could, however an int (System.Int32) is not big enough to hold every possible decimal value.

嗯,当然可以,但是 int (System.Int32) 不足以容纳所有可能的十进制值。

That means if you cast a decimal that's larger than int.MaxValue you will overflow, and if the decimal is smaller than int.MinValue, it will underflow.

这意味着如果你转换一个大于 int.MaxValue 的小数,你会溢出,如果小数小于 int.MinValue,它会下溢。

What happens when you under/overflow? One of two things. If your build is unchecked (i.e., the CLR doesn't care if you do), your application will continue after the value over/underflows, but the value in the int will not be what you expected. This can lead to intermittent bugs and may be hard to fix. You'll end up your application in an unknown state which may result in your application corrupting whatever important data its working on. Not good.

当你下/溢出时会发生什么?两件事之一。如果您的构建未被检查(即,CLR 不关心您是否这样做),您的应用程序将在值上溢/下溢后继续运行,但 int 中的值将不是您所期望的。这可能会导致间歇性错误并且可能难以修复。您的应用程序最终将处于未知状态,这可能会导致您的应用程序损坏其正在处理的任何重要数据。不好。

If your assembly is checked (properties->build->advanced->check for arithmetic overflow/underflow or the /checked compiler option), your code will throw an exception when an under/overflow occurs. This is probably better than not; however the default for assemblies is not to check for over/underflow.

如果您的程序集被检查(属性->构建->高级->检查算术溢出/下溢或 /checked 编译器选项),您的代码将在发生下/溢出时抛出异常。这可能总比没有好;然而,程序集的默认设置是不检查上溢/下溢。

The real question is "what are you trying to do?" Without knowing your requirements, nobody can tell you what you shoulddo in this case, other than the obvious: DON'T DO IT.

真正的问题是“你想做什么?” 在不知道您的要求的情况下,没有人可以告诉您在这种情况下该做什么,除了显而易见的:不要这样做。

If you specifically do NOT care, the answers here are valid. However, you should communicateyour understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an uncheckedblock

如果你特别不关心,这里的答案是有效的。但是,您应该传达您的理解,即可能会发生溢出,并且将您的强制转换代码包装在未经检查的块中并不重要

unchecked
{
  // do your conversions that may underflow/overflow here
}

That way people coming behind you understand you don't care, and if in the future someone changes your builds to /checked, your code won't break unexpectedly.

这样后面的人就会明白你不在乎,如果将来有人将你的构建更改为 /checked,你的代码不会意外中断。

Ifall you want to do is drop the fractional portion of the number, leaving the integral part, you can use Math.Truncate.

如果您只想去掉数字的小数部分,留下整数部分,您可以使用 Math.Truncate。

decimal actual = 10.5M;
decimal expected = 10M;
Assert.AreEqual(expected, Math.Truncate(actual));

回答by Mark Brackett

I prefer using Math.Round, Math.Floor, Math.Ceilingor Math.Truncateto explicitly set the rounding mode as appropriate.

我更喜欢使用Math.RoundMath.FloorMath.CeilingMath.Truncate来明确设置适当的舍入模式。

Note that they all return Decimal as well - since Decimal has a larger range of values than an Int32, so you'll still need to cast (and check for overflow/underflow).

请注意,它们也都返回 Decimal - 由于 Decimal 的值范围比 Int32 大,因此您仍然需要强制转换(并检查是否上溢/下溢)。

 checked {
   int i = (int)Math.Floor(d);
 }

回答by Timbo

I find that the casting operator does not work if you have a boxed decimal (i.e. a decimal value inside an object type). Convert.ToInt32(decimal as object) works fine in this case.

我发现如果您有一个装箱小数(即对象类型内的十进制值),则转换运算符不起作用。Convert.ToInt32(decimal as object) 在这种情况下工作正常。

This situation comes up when retrieving IDENTITY/AUTONUMBER values from the database:

从数据库中检索 IDENTITY/AUTONUMBER 值时会出现这种情况:

SqlCommand foo = new SqlCommand("INSERT INTO...; SELECT SCOPE_IDENTITY()", conn);
int ID = Convert.ToInt32(foo.ExecuteScalar());  // works
int ID = (int)foo.ExecuteScalar();              // throws InvalidCastException

See 4.3.2 Unboxing conversions

4.3.2 拆箱转换

回答by Timbo

decimal d = 5.5;

十进制d = 5.5

int i = decimal.ToInt32(d);// you will get i = 5

ref: link text

参考:链接文本

回答by sleepwalkerfx

Rounding a decimal to the nearest integer

将小数四舍五入到最接近的整数

decimal a ;
int b = (int)(a + 0.5m);

when a = 49.9, then b = 50

a = 49.9, 那么b = 50

when a = 49.5, then b = 50

a = 49.5, 那么b = 50

when a = 49.4, then b = 49etc.

什么时候a = 49.4,然后b = 49等等。