2012-08-27 20 views
1

四捨五入精確的雙重價值我想圓的雙重價值正是目前它讓我喜歡...如何使用Math.Round

val = 0.01618 

Math.Round(val,2) 

0.02(目前它給這樣的)。

0.01(我想要這樣)。

回答

0

您可以使用Math.Floor得到它您喜歡的值,然後使用Math.Round得到它的2位小數,就像這樣:

// Returns double that is rounded and floored 
double GetRoundedFloorNumber(double number, int rounding) 
{ 
    return ((Math.Floor(number * (Math.Pow(10, rounding)))/Math.Pow(10, rounding))); 

} 

所以調用這個函數應該返回權數:

示例代碼:

static void Main(string[] args) 
    { 
     // Writes 0.016 to the screen 
     Console.WriteLine(GetRoundedFloorNumber(0.01618, 3)); 
     Console.ReadLine(); 
    } 

    static double GetRoundedFloorNumber(double number, int rounding) 
    { 
     return ((Math.Floor(number * (Math.Pow(10, rounding)))/Math.Pow(10, rounding))); 

    } 
+0

謝謝你這麼多的工作 – nag

+0

一點問題都沒有:) –

+0

嗯,它沒有工作,當我給四捨五入作爲3仍然我得到0.01後舍入爲3,但它應該顯示0.016 – nag

3

Math.Floor()是你在找什麼,我想。如果你想舍入到兩個十進制符號,你可以做Math.Floor(v*100)/100。我想知道爲什麼沒有超過Floor的小數位數。

1

你想要的是Math.Floor()或類似的東西(不要沒有C#,抱歉)。這總是會下降。 Math.Round()像here那樣描述它。

0

這將舍入你想要的地方;

Math.Round(val - 0.005, 2)