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?

2
  • 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. Commented Jan 13, 2016 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. Commented Jan 13, 2016 at 12:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.