-1

I have floats like these,

0.0 , 50.0 ...

How do I convert them to:

0 , 50 ...

I need the meaningful numbers in the decimal part stay intact; so 13.59 must remain 13.59.

EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Shervin4030
  • 27
  • 1
  • 9

2 Answers2

1

So there are few ways to do this.

For your way I am pretty sure you could get away with a very naive solution.

Number formatToInt(float floating) {
   if (Math.ceil(floating) == Math.floor(floating)) {
       return (int)floating;
    } else {
       return floating;
    }
}
Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64
  • will you explain a little ? I dont understand mFloat, is that sth I can use in Android ? – Shervin4030 Dec 23 '13 at 16:14
  • won't compile : `Math` methods won't work with `Number`, why not just using `float` ? – kiruwka Dec 23 '13 at 16:15
  • I think he's just using the `Number` class, but you should be able to make `num` a `float` and this should work correctly. – But I'm Not A Wrapper Class Dec 23 '13 at 16:25
  • @Shervin4030 you are correct, it's a little confusing. I cleaned it up. Basically if the rounded up is the same as the bottom it can be safely truncated as an int, and otherwise it's a full float. I use the Number class since it's the only way to sort of treat the numbers as the same type. – Greg Giacovelli Dec 24 '13 at 09:30
1
    package com.ceil;

    public class TestCeil {
        public static void main(String[] args) {


            double[] doubleArray = {-100.76 , 80.0 , 192.23};
            Number number;
            for(int i=0; i<doubleArray.length; i++){
                if (Math.ceil(doubleArray[i]) == Math.floor(doubleArray[i])) {
                    number = (int) doubleArray[i];

                }else
                    number= doubleArray[i];
                System.out.println(number); 
            }       


        }

    }

Refer the Java API. Number is the super class of both Double and Integer:

http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

Output can be Integer or Double depending on the decimal place value.