It's not a secret anymore!*
The moose likes Beginning Java and the fly likes decimal part of a float Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "decimal part of a float" Watch "decimal part of a float" New topic
Author

decimal part of a float

fab etore
Greenhorn

Joined: Jul 01, 2002
Posts: 9
i would like to know how can i get the decimal part of a float. I think there must be a method for, by i can't find it.
please help me ;-)
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
float f;
....
float frac = f - (int)f;


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
fab etore
Greenhorn

Joined: Jul 01, 2002
Posts: 9
thanks
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Ron Newman:
float f;
....
float frac = f - (int)f;

That doesn't work well for f > Integer.MAX_VALUE.
Instead you should probably use
float frag = f - Math.ceil(f);


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
But that works properly only for negative numbers...
[ October 14, 2002: Message edited by: Ron Newman ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Of course I meant *floor*, not ceil... :roll:
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Or float % 1.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Dirk Schreckmann:
Or float % 1.

Wow, I didn't know that "%" was defined for floats in Java...
That's certainly the most appropriate solution.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: decimal part of a float
 
Similar Threads
All Vowels in an Integer
getting numberformatexception For input string: "500.0"
assiging int to float
narrowing primitive casts
SetPrecision?