简体   繁体   English

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

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

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

Use Convert.ToInt32 from mscorlib as in使用mscorlib中的Convert.ToInt32作为

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

See MSDN .请参阅MSDN You can also use Decimal.ToInt32 .您还可以使用Decimal.ToInt32 Again, see MSDN .再次,请参阅MSDN Finally, you can do a direct cast as in最后,您可以像这样进行直接转换

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

which uses the explicit cast operator.它使用显式转换运算符。 See MSDN .请参阅MSDN

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 (ie, 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.如果您的构建未被检查(即,CLR 不关心您是否这样做),您的应用程序将在值上溢/下溢后继续运行,但 int 中的值将不是您所期望的。 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.不好。

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.如果您的程序集被检查(属性->构建->高级->检查算术溢出/下溢或 /checked 编译器选项),您的代码将在发生下/溢出时抛出异常。 This is probably better than not;这可能总比没有好; however the default for assemblies is not to check for over/underflow.然而,程序集的默认设置是不检查上溢/下溢。

The real question is "what are you trying to do?"真正的问题是“你想做什么?” Without knowing your requirements, nobody can tell you what you should do 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 communicate your understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an unchecked block但是,您应该传达您的理解,即可能会发生溢出,并且将您的强制转换代码包装在未经检查的块中并不重要

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,你的代码不会意外中断。

If all 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));
int i = (int)d;

will give you the number rounded down.会给你四舍五入的数字。

If you want to round to the nearest even number (ie >.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#.通常,您可以在 C# 中的所有数字类型之间进行转换。 If there is no information that will be lost during the cast you can do it implicitly:如果在转换过程中没有信息会丢失,您可以隐式地进行:

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".在这里你失去了“.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.这可能没问题,但您必须明确说明它并进行明确的转换以表明您知道您可能会丢失信息。

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

This should work just fine.这应该工作得很好。

decimal vIn = 0.0M;
int vOut = Convert.ToInt32(vIn);

Here is a very handy convert data type webpage for those of others.这是一个非常方便的转换数据类型网页,供其他人使用。 http://www.convertdatatypes.com/Convert-decimal-to-int-in-CSharp.html http://www.convertdatatypes.com/Convert-decimal-to-int-in-CSharp.html

System.Decimal implements the IConvertable interface, which has a ToInt32() member. System.Decimal实现IConvertable接口,该接口具有ToInt32()成员。

Does calling System.Decimal.ToInt32() work for you?调用System.Decimal.ToInt32()对你System.Decimal.ToInt32()吗?

Rounding a decimal to the nearest integer将小数四舍五入到最接近的整数

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

when a = 49.9 , then b = 50a = 49.9 ,则b = 50

when a = 49.5 , then b = 50a = 49.5 ,则b = 50

when a = 49.4 , then b = 49 etc.a = 49.4 ,然后b = 49等等。

decimal d = 5.5 ;十进制d = 5.5 ;

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

ref: link text参考: 链接文本

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

I prefer using Math.Round , Math.Floor , Math.Ceiling or Math.Truncate to 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);
 }

I find that the casting operator does not work if you have a boxed decimal (ie 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 conversions4.3.2 拆箱转换

No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.似乎没有答案处理来自尝试转换 int 范围之外的小数的 OverflowException/UnderflowException。

int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));

This solution will return the maximum or minimum int value possible if the decimal value is outside the int range.如果十进制值超出 int 范围,此解决方案将返回可能的最大或最小 int 值。 You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.当值在 int 范围内时,您可能希望使用 Math.Round、Math.Ceiling 或 Math.Floor 添加一些舍入。

Convert decimal to integer将十进制转换为整数

decimal decimalValue=5.00;
int intValue=Convert.ToInt32(decimalValue);

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

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