vnshetty vnshetty - 4 years ago 171
Android Question

How to remove the decimal part from a float number that contains .0 in java

I just want to remove the fractional part of a float number that contains .0. All other numbers are acceptable..
For example :

I/P: 1.0, 2.2, 88.0, 3.56666, 4.1, 45.00 , 99.560
O/P: 1 , 2.2, 88, 3.567, 4.1, 45 , 99.560


Is there any method available to do that other than "comparing number with ".0" and taking substring" ?

EDIT :
I don't want ACTING FLOAT NUMBERs (like 1.0, 2.0 is nothing but 1 2 right?)

I feel my question is little confusing...

Here is my clarification: I just want to display a series of floating point numbers to the user. If the fractional part of a number is zero, then display only the integer part, otherwise display the number as it is. I hope it's clear now..

Answer Source

You could use a regular expression such as this: \\.0+$. If there are only 0's after the decimal point this regular expression will yield true.

Another thing you could do is something like so:

float x = 12.5;
float result = x - (int)x;
if (result != 0)
{
    //If the value of `result` is not equal to zero, then, you have a decimal portion which is not equal to 0.
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download