4

したい の位は四捨五入してい10ます。たとえば、 のような数値17.3は に丸められ20.0ます。有効数字3桁を許可したい。プロセスの最後のステップとして、パーセントの最も近い 10 分の 1 に丸めることを意味します。

サンプル:

    the number is 17.3 ,i want round to 20 ,

    and this number is 13.3 , i want round to 10 ?

これどうやってするの ?

4

5 に答える 5

5

Chris Charabaruk があなたの望む答えをここで教えてくれます

コアに到達するために、拡張メソッドとしての彼のソリューションを次に示します。

public static class ExtensionMethods
{
    public static int RoundOff (this int i)
    {
        return ((int)Math.Round(i / 10.0)) * 10;
    }
}

int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10

//編集: このメソッドは int 値に対してのみ機能します。このメソッドを好みに合わせて編集する必要があります。fe: public static class ExtensionMethods

{
    public static double RoundOff (this double i)
    {
       return (Math.Round(i / 10.0)) * 10;
    }
}

/edit2: Corak が述べたように、使用する必要がある/使用できる

Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10
于 2013-08-21T06:12:51.310 に答える
3

他の答えも正しいですが、なしでそれを行う方法は次のMath.Roundとおりです。

((int)((17.3 + 5) / 10)) * 10 // = 20
((int)((13.3 + 5) / 10)) * 10 // = 10
((int)((15.0 + 5) / 10)) * 10 // = 20
于 2013-08-21T06:19:29.813 に答える
0

これを試して-

double d1 = 17.3;
int rounded1 = ((int)Math.Round(d/10.0)) * 10; // Output is 20

double d2 = 13.3;
int rounded2 = ((int)Math.Round(d/10.0)) * 10; // Output is 10
于 2013-08-21T06:16:20.253 に答える
0
double Num = 16.6;
int intRoundNum = (Convert.ToInt32(Math.Round(Num / 10)) * 10);
Console.WriteLine(intRoundNum);
于 2013-08-21T06:18:33.663 に答える
0

数学ライブラリのキャストやプルを避けたい場合は、モジュラス演算子を使用して次のようにすることもできます。

int result = number - (number % 10);
if (number % 10 >= 5)
{
    result += 10;
}

あなたの与えられた数字のために:

番号 処理 結果
13.3 13.3 - (3.3) 10
17.3 17.3 - (7.3) + 10 20
于 2021-01-15T20:02:18.253 に答える