簡體   English   中英

在C#中舍入到小數點后1位

[英]Round to 1 decimal place in C#

我想將我的答案舍入小數點后1位。 例如:6.7,7.3等。但是當我使用Math.round時,答案總是沒有小數位。 例如:6,7

這是我使用的代碼:

int [] nbOfNumber = new int[ratingListBox.Items.Count];
int sumInt = 0;
double averagesDoubles;

for (int g = 0; g < nbOfNumber.Length; g++)
{
    nbOfNumber[g] = int.Parse(ratingListBox.Items[g].Text);
}

for (int h = 0; h < nbOfNumber.Length; h++)
{
    sumInt += nbOfNumber[h];
}

averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);
averageRatingTextBox.Text = averagesDoubles.ToString();

你用一個int除以它會得到一個int作為結果。 (這使得13/7 = 1)

首先嘗試將其轉換為浮點:

averagesDoubles = (sumInt / (double)ratingListBox.Items.Count);

averagesDoubles = Math.Round(averagesDoubles, 2); 對於舍入雙值是負責任的。 它會循環, 5.9765.98 ,但這不會影響值的表示。

ToString()負責小數的表示。

試試:

averagesDoubles.ToString("0.0");

根據Math.Round的定義,驗證averagesDoubles是double還是decimal,並將這兩行組合在一起:

averagesDoubles = (sumInt / ratingListBox.Items.Count);
averagesDoubles = Math.Round(averagesDoubles, 2);

至 :

averagesDoubles = Math.Round((sumInt / ratingListBox.Items.Count),2);

上述情況中的2表示要向上舍入的小數位數。 請查看上面的鏈接以獲取更多參考。

int division將始終忽略分數

 (sumInt / ratingListBox.Items.Count); 

這里sunint是int,ratingListBox.Items.Coun也是int,所以divison永遠不會產生分數

要獲得分數中的值,您需要像float這樣的數據類型和類型轉換sumInt並計數浮點數和雙精度然后使用divison

var val = Math.Ceiling(100.10m); 結果101

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM