Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round double to nearest whole number and then convert to a float?

Tags:

java

rounding

I am using java.util.Random to generate a random gaussian. I need to convert this gaussian to a float value. However gaussian is a double, so I need some way to either round then convert it to a float. I need to round to the nearest whole number, rounding up. Here is my question: How?

like image 402
JAW1025 Avatar asked Nov 22 '11 22:11

JAW1025


People also ask

How do you round a float in Java?

In order to round float and double numbers in Java, we use the java. lang. Math. round() method.


1 Answers

float b = (float)Math.ceil(a); or float b = (float)Math.round(a);

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

like image 123
Paul Tomblin Avatar answered Sep 28 '22 08:09

Paul Tomblin