Yogesh Byndoor
Yogesh Byndoor

Reputation: 181

Math operations on integer or floating point values

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?

Upvotes: 0

Views: 68

Answers (2)

cdaiga
cdaiga

Reputation: 4937

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

Upvotes: 2

LordAnomander
LordAnomander

Reputation: 1123

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.

Upvotes: 2

Related Questions