2013-09-30 17 views
8

Vorrei arrotondare la mia risposta con 1 decimale. ad esempio: 6.7, 7.3, ecc. Ma quando uso Math.round, la risposta viene sempre senza cifre decimali. Ad esempio: 6, 7Rotondo al 1 decimale in C#

Ecco il codice che ho usato:

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(); 
+0

vostre variabili non sono definite –

+0

modificati ... grazie –

+0

http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to- due decimali-posti-in-c – Transcendent

risposta

31

Stai dividendo per un int, wil dare un int come risultato. (che rende 13/7 = 1)

Prova a trasmettere ad un punto prima flottante:

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

Il averagesDoubles = Math.Round(averagesDoubles, 2); è reponsible per arrotondare il valore doppio. Arrotonda, 5.976 a 5.98, ma ciò non influisce sulla presentazione del valore.

Il ToString() è responsabile della presentazione dei decimali.

Prova:

averagesDoubles.ToString("0.0"); 
4

Sei verificare che averagesDoubles è o doppia o decimale secondo la definizione di Math.Round e combinare queste due linee:

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

TO:

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

2 nel caso di cui sopra rappresenta il nu mber di decimali che vuoi arrotondare. Controlla il link qui sopra per maggiori informazioni.

1

divisione int sarà sempre ignorare frazione

(sumInt/ratingListBox.Items.Count); here sunint is int and ratingListBox.Items.Coun is also int , so divison never results in fraction 

to get the value in fraction , you need to datatype like float and type cast the sumInt and count to float and double and then use divison