[英]Best way to get whole number part of a Decimal number
返回小数的整数部分的最佳方法是什么(在c#中)? (这必须适用于可能不适合int的非常大的数字)。
GetIntPart(343564564.4342) >> 343564564
GetIntPart(-323489.32) >> -323489
GetIntPart(324) >> 324
这样做的目的是:我插入数据库中的十进制(30,4)字段,并希望确保我不会尝试插入一个数字而不是字段太长。 确定小数的整数部分的长度是该操作的一部分。
顺便说一下,(int)Decimal.MaxValue会溢出。 你不能得到十进制的“int”部分,因为小数太大而无法放入int框中。 刚刚检查过......它甚至太长了(Int64)。
如果你想要一个十进制值的位到点的左边,你需要这样做:
Math.Truncate(number)
并将值返回为...... DECIMAL或DOUBLE。
编辑:Truncate绝对是正确的功能!
我认为System.Math.Truncate就是你要找的东西。
取决于你在做什么。
例如:
//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6
要么
//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7
默认值始终是前者,这可能是一个惊喜,但非常有意义 。
你明确的演员会做:
int intPart = (int)343564564.5
// intPart will be 343564564
int intPart = (int)343564565.5
// intPart will be 343564566
从你说出这个问题的方式来看,这听起来并不是你想要的 - 你想每次都把它放在地板上。
我会做:
Math.Floor(Math.Abs(number));
还要检查decimal
的大小 - 它们可能非常大,所以你可能需要使用很long
decimal
。
分离值及其小数部分值的非常简单的方法。
double d = 3.5;
int i = (int)d;
string s = d.ToString();
s = s.Replace(i + ".", "");
s是小数部分= 5和
我是整数= 3的值
你只需要投射它,如下:
int intPart = (int)343564564.4342
如果您仍想在以后的计算中将其用作小数,那么Math.Truncate(如果您想要负数的特定行为,则可能是Math.Floor)是您想要的功能。
我希望能帮助你。
/// <summary>
/// Get the integer part of any decimal number passed trough a string
/// </summary>
/// <param name="decimalNumber">String passed</param>
/// <returns>teh integer part , 0 in case of error</returns>
private int GetIntPart(String decimalNumber)
{
if(!Decimal.TryParse(decimalNumber, NumberStyles.Any , new CultureInfo("en-US"), out decimal dn))
{
MessageBox.Show("String " + decimalNumber + " is not in corret format", "GetIntPart", MessageBoxButtons.OK, MessageBoxIcon.Error);
return default(int);
}
return Convert.ToInt32(Decimal.Truncate(dn));
}
Public Function getWholeNumber(number As Decimal) As Integer
Dim round = Math.Round(number, 0)
If round > number Then
Return round - 1
Else
Return round
End If
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.