-4

How do I round a float number if it returns a whole value? And, how do I round if it's like: 5/2 = 2.5 and NOT like this: 5/2 = 2.50000000

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69

3 Answers3

4

A double does not allow you to specify the number of decimal places it has; you may be able to set as many as you wish to 0, but they are still there. (Note that, mathematically, the two values you show for 5/2 are the same.) What you can do is control how many get displayed; since you haven't specified how you are attempting to display this value, I can't help in how to modify it to limit the number of decimal places to show.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Whenever needed, you can make some modifications on your double, such as using the setRoundingMode method of DecimalFormat class, along with the RoundingMode enum.

As mentioned before though, 2.5 is the same with 2.500000 in a double, you do not have to change its digits.

I guess you are trying to print your double and you get a number of unwanted digits in the output. In that case, I suggest though that you convert your double into a formatted string and use it as such:

System.out.println(String.format("%.2f", myDouble));
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
0

You are a bit confused I think...
2.5 and 2.50000000 are the exact same thing!
They are just written differently.

I don't really understand what you are trying to achieve but you can round floats like this:

float result = Math.round(someFloat);

If you always want to round up or down regardless of what the number is use:

float result = (float)Math.ceil(someFloat);

or

float result = (float)Math.floor(someFloat);