Domanda

Come si converte un doppio nell'int più vicino?

È stato utile?

Soluzione

Usa Math.round () , possibilmente in combinazione con MidpointRounding.AwayFromZero

es:

Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3

Altri suggerimenti

double d = 1.234;
int i = Convert.ToInt32(d);

Riferimento

Gestisce l'arrotondamento in questo modo:

  

arrotondato all'intero con segno a 32 bit più vicino. Se il valore è a metà strada   tra due numeri interi, viene restituito il numero pari; cioè 4.5   viene convertito in 4 e 5.5 viene convertito in 6.

Puoi anche usare la funzione:

//Works with negative numbers now
static int MyRound(double d) {
  if (d < 0) {
    return (int)(d - 0.5);
  }
  return (int)(d + 0.5);
}

A seconda dell'architettura, è più volte più veloce.

double d;
int rounded = (int)Math.Round(d);

So che questa domanda è vecchia, ma mi sono imbattuto nella mia ricerca della risposta alla mia domanda simile. Ho pensato di condividere il consiglio molto utile che mi è stato dato.

Quando si converte in int, aggiungere semplicemente .5 al proprio valore prima di effettuare il downcast. Poiché il downcasting in int scende sempre al numero più basso (es. (Int) 1.7 = 1), se il tuo numero è .5 o superiore, l'aggiunta di .5 lo farà apparire nel numero successivo e il tuo downcast in int dovrebbe restituire il valore corretto . (ad es. (int) (1.8 + .5) = 2)

Spero che questa risposta sia utile a chiunque.

Per Unity, utilizza Mathf.RoundToInt .

using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.0f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.2f));
        // Prints 11
        Debug.Log(Mathf.RoundToInt(10.7f));
        // Prints 10
        Debug.Log(Mathf.RoundToInt(10.5f));
        // Prints 12
        Debug.Log(Mathf.RoundToInt(11.5f));

        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.0f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.2f));
        // Prints -11
        Debug.Log(Mathf.RoundToInt(-10.7f));
        // Prints -10
        Debug.Log(Mathf.RoundToInt(-10.5f));
        // Prints -12
        Debug.Log(Mathf.RoundToInt(-11.5f));
    }
}

public static int RoundToInt(float f) { return (int)Math.Round(f); }

Sto sviluppando un calcolatore scientifico che sfoggia un pulsante Int. Ho scoperto che la seguente è una soluzione semplice e affidabile:

double dblInteger;
if( dblNumber < 0 )
   dblInteger = Math.Ceiling(dblNumber);
else
   dblInteger = Math.Floor(dblNumber);

Math.Round talvolta produce risultati imprevisti o indesiderabili e la conversione esplicita in numero intero (tramite cast o Convert.ToInt ...) spesso produce valori errati per numeri di precisione più elevata. Il metodo sopra sembra funzionare sempre.

scroll top