Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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..

like image 367
vnshetty Avatar asked May 08 '12 10:05

vnshetty


People also ask

How do you remove the decimal part of a number?

Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.

How do I fix the number of decimal places in Java?

Method 1: Using the format() Method of the String class We can use format() method of String class to format the decimal number to some specific format.


1 Answers

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.
}
like image 193
npinti Avatar answered Sep 29 '22 12:09

npinti