Il metodo Java Math round () arrotonda il valore specificato al valore int o long più vicino e lo restituisce.
Cioè, 1.2 è arrotondato a 1 e 1.8 è arrotondato a 2 .
La sintassi del round()
metodo è:
Math.round(value)
Ecco round()
un metodo statico. Quindi, stiamo accedendo il metodo che utilizza il nome della classe, Math
.
round () Parametri
Il round()
metodo accetta un singolo parametro.
- valore - numero che deve essere arrotondato
Nota : il tipo di dati del valore deve essere float
o double
.
round () Valore restituito
- restituisce il
int
valore se l'argomento èfloat
- restituisce il
long
valore se l'argomento èdouble
Il round()
metodo:
- arrotonda per eccesso se il valore dopo il decimale è maggiore o uguale a 5
1.5 => 2 1.7 => 2
- arrotonda per difetto se il valore dopo il decimale è minore di 5
1.3 => 1
Esempio 1: Java Math.round () con double
class Main ( public static void main(String() args) ( // Math.round() method // value greater than 5 after decimal double a = 1.878; System.out.println(Math.round(a)); // 2 // value equals to 5 after decimal double b = 1.5; System.out.println(Math.round(b)); // 2 // value less than 5 after decimal double c = 1.34; System.out.println(Math.round(c)); // 1 ) )
Esempio 2: Java Math.round () con float
class Main ( public static void main(String() args) ( // Math.round() method // value greater than 5 after decimal float a = 3.78f; System.out.println(Math.round(a)); // 4 // value equals to 5 after decimal float b = 3.5f; System.out.println(Math.round(b)); // 4 // value less than 5 after decimal float c = 3.44f; System.out.println(Math.round(c)); // 3 ) )
Tutorial consigliati
- Math.floor ()
- Math.ceil ()