Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.round gives a decimal number in android

Tags:

java

android

math

I have this fuction:

enemigo.posZ = 5.1529696E8 //This is the value at runtime, it's a float.
double posicionZ = Math.round(enemigo.posZ*100.0f)/100.0f;

And this is the output, but why? It should round it to an integer!

posicionZ = 2.1474836E7
like image 609
D4rWiNS Avatar asked Nov 20 '25 09:11

D4rWiNS


1 Answers

An integer with a lot of digits that begins with 21474... should be a clue!

Java has two versions of Math.round():

public static int Math.round(float a)    // float  -> 32-bit int
public static long Math.round(double a)  // double -> 64-bit long

Let's look at the code:

double posicionZ = Math.round(enemigo.posZ * 100.0f) / 100.0f;

Since enemigo.posZ is a float, the first version is used. It wants to return enemigo.posZ * 100.0, or 51529696000.0, as a 32-bit int, but it can't because it overflows. So it returns Integer.MAX_VALUE, or 2^³¹ - 1 = 2147483647. Then the divison by 100.0f returns 21474836.0, which is 2.1474836E7.

like image 58
Adam Liss Avatar answered Nov 21 '25 21:11

Adam Liss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!