Cómo convertir float a int con Java


Usé la siguiente línea para convertir float a int, pero no es tan precisa como me gustaría:

 float a=8.61f;
 int b;

 b=(int)a;

El resultado es: 8 (Debería ser 9)

Cuando a = -7.65f, el resultado es: -7 (Debería ser -8)

¿Cuál es la mejor manera de hacerlo ?

Author: Ja͢ck, 2009-08-18

6 answers

Usando Math.round() redondeará el flotador al entero más cercano.

 587
Author: tw39124,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-07 18:03:57

En realidad, hay diferentes maneras de bajar float a int, dependiendo del resultado que desee lograr: (para int i, float f)

  • Round (el entero más cercano al flotador dado)

    i = Math.round(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    Nota: esto es, por contrato, igual a (int) Math.floor(f + 0.5f)

  • Truncar (es decir, soltar todo después del punto decimal)

    i = (int) f;
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • Ceil / floor (un entero siempre mayor / menor que un valor dado si tiene cualquier fracción part)

    i = (int) Math.ceil(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    i = (int) Math.floor(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

Para redondear valores positivos, también puede usar (int)(f + 0.5), que funciona exactamente como Math.Round en esos casos (según doc).

En teoría se podría usar Math.rint(f) para hacer el redondeo, pero rint no redondea 0.5 hacia arriba, lo redondea hacia arriba o hacia abajo, cualquiera de los enteros inferior o superior es par, por lo que es inútil en la mayoría caso.

Véase

Http://mindprod.com/jgloss/round.html

Http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

Para más información y algunos ejemplos.

 168
Author: vaxquis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-26 17:45:20

Math.round(value) redondee el valor al número entero más cercano.

Use

1) b=(int)(Math.round(a));

2) a=Math.round(a);  
   b=(int)a;
 13
Author: SHUNMUGA RAJ PRABAKARAN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-15 09:47:19

Use Math.round(value) luego, después de escribir, lo convierte en entero.

float a = 8.61f;
int b = (int)Math.round(a);
 5
Author: Sachithra Sewwandi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-03 18:01:49

Math.round también devuelve un valor entero, por lo que no es necesario encasillar.

int b = Math.round(float a);
 2
Author: venkat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 13:02:56

En cuanto a mí, más fácil: (int) (a+.5) / / a es un flotador. Devuelve el valor redondeado.

No depende de Java Math.round () types

 0
Author: Bruno L.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-22 00:21:18