Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding Math.round()  RSS feed

 
Ananth Majumdar
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the code below

class Jcp377
{
public static void main(String[] args)
{
float f7 = -2147483645.5f;
System.out.println("Round f7 is " + Math.round(f7));
}
}

Math.round() is returning incorrect values..
like for -2147483645.5f it should return -2147483645 but it is returning
-2147483648 and its returning unpredictable values... Please Explain!!!
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should understand that the precision of the types float and double is limited. You cannot store numbers with an arbitrary number of digits in a float or double and expect them to hold the value exactly.

So, the behaviour you see is normal.

The precision of a float is about 6 decimal digits, so if you put a number with 11 decimal digits like -2147483645.5 in a float, it will not work as you expect.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Math.round() is corect. -2147483645.5f cannot be represented accurately in float so it is stored as closest float value which is -2147483648.0.
This "rounding" is done when compiler parses the literal -2147483645.5f and creates a float constant from it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!