0

I can explain this with an example.

Consider the floating point values like 2.0, 3.0 e.t.c the output must the number i.e 2, 3 e.t.c

If the floating point values are like 2.1, 3.5 e.t.c the output remain the same i.e 2.1, 3.5

Is there any Math operation on floating point values to do this?

  • You want an operation that converts some floats to integers and other floats to floats? Java method signatures can't vary only in their return types so that doesn't sound possible. – sisyphus Jan 13 '16 at 11:27
  • You are talking about how you want to format a number as a string. This is not a maths function as 2.0 == 2 so there is no change mathematically. – Peter Lawrey Jan 13 '16 at 12:17

2 Answers2

2

You can easily check if a float has decimal places.

if (number % (int) number == 0)
     System.out.println((int) number); // you know it has no decimal places
else
     System.out.println(number); // it has decimal places and you want to print them

The link provided by Seffy Golan suggests an even better solution, by simply comparing

if (number == (long) number) { ... }

I thought I'd take it into my answer as it is a nice approach I wasn't aware of.

Community
  • 1
  • 1
LordAnomander
  • 1,103
  • 6
  • 16
2

I think @LordAnomander answer is good, but a bit costly, try using:

if (number - (int) number == 0)
 System.out.println((int) number); // you know it has no decimal places
else
 System.out.println(number); // it has decimal places and you want to print them
cdaiga
  • 4,861
  • 3
  • 22
  • 42