質問

(C#で) 小数の整数部分を返す最良の方法は何ですか?(これは、int に収まらない可能性のある非常に大きな数値に対して機能する必要があります)。

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

この目的は次のとおりです。データベース内の 10 進数 (30,4) フィールドに挿入していますが、フィールドに対して長すぎる数値を挿入しないようにしたいと考えています。小数の整数部分の長さの決定は、この操作の一部です。

役に立ちましたか?

解決

みんな、(int型)Decimal.MaxValueがオーバーフローしますところで。小数はint型のボックスに入れて大きなすぎfriggenあるので、あなたは、小数点以下の「INT」の部分を取得することはできません。ただ、チェックし...(Int64の)長いためにそのさえ大きすぎます。

あなたは、ドットの左に小数点値のビットをしたい場合は、

、あなたがこれを行う必要があります:

Math.Truncate(number)

として... DECIMALまたはDOUBLE値を返します。

の編集:!切り捨ては間違いなく正しい関数である

他のヒント

私は 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.

あなただけのような、それをキャストする必要があります:

int intPart = (int)343564564.4342

あなたはまだ、その後Math.Truncate、後の計算で小数点としてそれを使用したい場合(あるいはMath.Floorあなたが負の数のために特定の行動をしたい場合)あなたが欲しい機能です。

別の値とその小数部の値に非常に簡単ます。

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

Sが端数部分= 5と
あります iは整数値である= 3

私はあなたを助けることを願っています。

/// <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帰属
所属していません StackOverflow
scroll top