0

I have tried to do this - Making any float value to int value. What I tried to achieve is make it 2.00-2.99 goes to 2.

Note: Im not trying to do Approximation (lower than 2.49 goes to 2, and those 2.50+ goes to 3).

I have done this so far

public int RemoveDecimal(float value)
{
    string TempText = (string)value;
    TempText.Remove(IndexOf('.'));
    return int.parse(TempText);
}

But this will get an error when the float value ends with .00

How can I achieve this?

Thanks for any help

4

3 に答える 3

5

Math.Floor is the function you need.

It:

Returns the largest integer less than or equal to the specified number.

Example:

var val = Math.Floor(value);

Or, you could simply cast to an integer - this will simply ignore the decimal portion, so long as the range of the decimal is within the range of an int (otherwise you will get an exception):

int noDecimals = (int)value;
于 2012-05-26T07:43:58.570 に答える
0

の値のほとんどがの範囲外であるため、常に afloatを に変換できるとは限りません。文字列を返す必要があります。intfloatint

以下はまさにそれを行います。

public string RemoveDecimal(float value)
{
    string TempText = value.ToString("#");
    return TempText;
}
于 2012-05-26T08:29:30.813 に答える
-2

浮動小数点数を int にキャストするだけで、必要なことが行われます。

i = (int)myFloat;

小数桁を切り捨てます。つまり、常に の方向に進み0ます。

(int)2    ==  2
(int)1.9  ==  1
(int)-1.5 == -1

結果が の有効範囲外の場合、これは明らかに正しく機能しませんint。同じことを達成したいが、結果として浮動小数点数Math.Truncateが必要な場合は、それが必要です。

于 2012-05-26T08:13:23.653 に答える