• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Regarding Math.round()

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!!!
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic