2012-10-31 13 views
27

Non lo so, la mia nomenclatura è corretta! In ogni caso, questi sono i numeri interi che ho, per esempio:Come arrotondare un numero intero a centinaia?

76 
121 
9660 

e mi piacerebbe a loro arrotondare fino alla fine cento, come ad esempio devono diventare:

100 
100 
9700 

Come posso farlo più veloce in C#? Penso ad un algoritmo, ma forse ci sono alcune utilità su C#?

+8

@RoyDictus Ha provato StackOverflow! –

+0

@HaLaBi: hahaha! Sì, stavo provando con una soluzione stretta @ L.B (elimina il post, non so: 'var newi = (int) Math.Round (oldi/100d) * 100;'). Penso che questo sia il modo migliore ... – markzzz

+1

@markzzz Che dire di 50? 0 o 100? – nawfal

risposta

49

Provare il metodo Math.Round. Ecco come:

Math.Round(76d/100d, 0) * 100; 
Math.Round(121d/100d, 0) * 100; 
Math.Round(9660d/100d, 0) * 100; 
+0

Questa è la soluzione più semplice da comprendere dal lotto. +1! Non si richiede il sovraccarico per specificare '0' però. Potrebbe essere possibile utilizzare meglio il sovraccarico di arrotondamento del punto intermedio – nawfal

+2

Utilizzare il decimale, non il doppio per questo. – CodesInChaos

+0

Non penso che funzioni come la maggior parte della gente si aspetta! 'Math.Round' troncherà il valore in modo che' Math.Round (50d/100d, 0) 'sarà 0. Alcune persone potrebbero aspettarsi che sia 100. –

13

Prova questa espressione:

(n + 50)/100 * 100 
+0

Questa è la risposta corretta. La domanda è stata fatta sui numeri interi. – Enigmativity

19

Ho scritto un metodo semplice estensione di generalizzare questo tipo di arrotondamento qualche tempo fa:

public static class MathExtensions 
{ 
    public static int Round(this int i, int nearest) 
    { 
     if (nearest <= 0 || nearest % 10 != 0) 
      throw new ArgumentOutOfRangeException("nearest", "Must round to a positive multiple of 10"); 

     return (i + 5 * nearest/10)/nearest * nearest; 
    } 
} 

Esso sfrutta divisione intera per trovare l'arrotondamento più vicino.

Esempio utilizzo:

int example = 152; 
Console.WriteLine(example.Round(100)); // round to the nearest 100 
Console.WriteLine(example.Round(10)); // round to the nearest 10 

E nel tuo esempio:

Console.WriteLine(76.Round(100)); // 100 
Console.WriteLine(121.Round(100)); // 100 
Console.WriteLine(9660.Round(100)); // 9700 
+1

Cosa darebbe per '51.Round (-10)'? –

+1

+1 Per un metodo di estensione molto pratico! – 3aw5TZetdf

+0

@ L.B L'ho provato e mi ha dato 40. – 3aw5TZetdf

0
int num = 9660; 
int remainder = num % 100; 
Console.WriteLine(remainder < 50 ? num - remainder : num + (100 -remainder)); 

Nota: non ho ancora testato questo fondo.

5

So che questo è un thread precedente. Ho scritto un nuovo metodo. Spero che questo sia utile per qualcuno.

public static double Round(this float value, int precision) 
    { 
     if (precision < -4 && precision > 15) 
      throw new ArgumentOutOfRangeException("precision", "Must be and integer between -4 and 15"); 

     if (precision >= 0) return Math.Round(value, precision); 
     else 
     { 
      precision = (int)Math.Pow(10, Math.Abs(precision)); 
      value = value + (5 * precision/10); 
      return Math.Round(value - (value % precision), 0); 
     } 
    } 

Esempio:

float value = F6666.677777; 
Console.Write(value.Round(2)) // = 6666.68 
Console.Write(value.Round(0)) // = 6667 
Console.Write(value.Round(-2)) // = 6700 
6

Solo un po 'oltre a @krizzzn 's risposta accettata ...

notano che la seguente restituirà 0:

Math.Round(50d/100d, 0) * 100; 

Considerare l'utilizzo il seguente e farlo restituire 100 invece:

Math.Round(50d/100d, 0, MidpointRounding.AwayFromZero) * 100; 

A seconda di quello che stai facendo, usando decimali potrebbe essere una scelta migliore (si noti la m):

Math.Round(50m/100m, 0, MidpointRounding.AwayFromZero) * 100m; 
1

Ciao io scrivo questa estensione questo diventa il prossimo cento per ogni numero passare

/// <summary> 
    /// this extension gets the next hunfìdred for any number you whant 
    /// </summary> 
    /// <param name="i">numeber to rounded</param> 
    /// <returns>the next hundred number</returns> 
    /// <remarks> 
    /// eg.: 
    /// i = 21 gets 100 
    /// i = 121 gets 200 
    /// i = 200 gets 300 
    /// i = 1211 gets 1300 
    /// i = -108 gets -200 
    /// </remarks> 
    public static int RoundToNextHundred(this int i) 
    { 
     return i += (100 * Math.Sign(i) - i % 100); 
     //use this line below if you want RoundHundred not NEXT 
     //return i % 100 == byte.MinValue? i : i += (100 * Math.Sign(i) - i % 100); 
    } 

    //and for answer at title point use this algoritm 
    var closeHundred = Math.Round(number/100D)*100; 

    //and here the extension method if you prefer 

    /// <summary> 
    /// this extension gets the close hundred for any number you whant 
    /// </summary> 
    /// <param name="number">number to be rounded</param> 
    /// <returns>the close hundred number</returns> 
    /// <remarks> 
    /// eg.: 
    /// number = 21 gets 0 
    /// number = 149 gets 100 
    /// number = 151 gets 200 
    /// number = -149 gets -100 
    /// number = -151 gets -200 
    /// </remarks> 
    public static int RoundCloseHundred(this int number) 
    { 
     return (int)Math.Round(number/100D) * 100; 
    } 
+0

Questo algoritmo in realtà non arrotonda, ma cerca il valore successivo dove 'valore% 100 == 0', ad es quando questo metodo viene chiamato con i = 200, restituisce 300. – feO2x

+0

E non funziona con valori negativi: quando questo metodo viene chiamato con i = -4, restituisce 100, anche se mi aspetterei che 0. – feO2x

+0

è corretto Quali sono i prossimi cento di 200? 300 – luka

0

Se si desidera solo numeri interi tondi fino (come l'OP effettivamente fatto), allora si può ricorrere a questa soluzione:

public static class MathExtensions 
{ 
    public static int RoundUpTo(this int number, int nearest) 
    { 
     if (nearest < 10 || nearest % 10 != 0) 
      throw new ArgumentOutOfRangeException(nameof(nearest), $"{nameof(nearest)} must be a positive multiple of 10, but you specified {nearest}."); 

     int modulo = number % nearest; 
     return modulo == 0 ? number : modulo > 0 ? number + (nearest - modulo) : number - modulo; 
    } 
} 

Se si desidera eseguire arrotondamenti a virgola mobile (o decimale), ricorrere alle risposte di @krizzzn e @Jim Aho.

Problemi correlati