获取十进制数的整数部分的最佳方法

问题描述 投票:0回答:8

返回小数的整数部分的最佳方法是什么(在 C# 中)? (这必须适用于可能不适合 int 的非常大的数字)。

GetIntPart(343564564.4342) >> 343564564
GetIntPart(-323489.32) >> -323489
GetIntPart(324) >> 324

这样做的目的是:我要插入数据库中的十进制 (30,4) 字段,并希望确保我不会尝试插入比该字段太长的数字。确定小数的整数部分的长度是这个操作的一部分。

c# .net decimal int
8个回答
236
投票

顺便说一下,(int)Decimal.MaxValue 会溢出。您无法获得小数的“int”部分,因为小数太大而无法放入 int 框中。刚刚检查过......它甚至太大了很长时间(Int64)。

如果你想要小数点左边的位,你需要这样做:

Math.Truncate(number)

并将值返回为... DECIMAL 或 DOUBLE。

编辑:截断绝对是正确的功能!


27
投票

我认为 System.Math.Truncate 是您要找的东西。


5
投票

取决于你在做什么。

例如:

//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
.


1
投票

你只需要像这样投它:

int intPart = (int)343564564.4342

如果您仍然想在以后的计算中将它用作小数,那么 Math.Truncate(如果您想要负数的特定行为,则可能是 Math.Floor)是您想要的函数。


1
投票

希望对你有帮助

/// <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));
}

0
投票

分离值及其小数部分值的非常简单的方法。

double  d = 3.5;
int i = (int)d;
string s = d.ToString();
s = s.Replace(i + ".", "");

s 是小数部分 = 5 和
i 是整数值 = 3


0
投票
   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

0
投票

忘记术语的含义:“整数”在答案和问题中似乎很常见。

从数字中得到整数:4 很简单:

1 x 4 = 4 <- A Whole Number! The first Whole Number!
2 x 4 = 8 <- A Whole Number!
3 x 4 = 12 <- A Whole Number!

四舍五入,取整数是取整数的秘籍!四舍五入删除数字的非整数部分!

1.3 x 4 = 5.2 <- NOT a Whole Number!
1 x 343564564.4342 <- NOT a Whole Number!

了解什么是整数很重要!

4 / 1 = 4 <- A Whole Number!
4 / 2 = 2 <- A Whole Number!
4 / 3 = 1.333 recurring  <- NOT A Whole Number!

请更准确地回答问题......

© www.soinside.com 2019 - 2024. All rights reserved.