Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast from double to int round off the top

Tags:

java

casting

I have got code:

double dd=2.99;
int ii=(int)(dd);//ii==2

I would like to have 3 in ii. Is there any fast and simple method?

like image 987
user1519221 Avatar asked Dec 19 '25 19:12

user1519221


2 Answers

You want Math.round() or - if you always want to round up - Math.ceil(). Similarly, there is a Math.floor() to always round down.

Being really picky, you should note that Math.round( double ) returns a long, so there is a possible loss of precision if you want to store the result in an int (for really large doubles).

like image 148
Anders R. Bystrup Avatar answered Dec 22 '25 08:12

Anders R. Bystrup


Use Math.ceil(dd). It'll round any number up to the nearest integer. Likewise, Math.floor(dd) would round it down while Math.round(dd) would round down/up depending on which is closer.

For the record, the Math class contains loads of useful mathematical methods.

like image 27
BambooleanLogic Avatar answered Dec 22 '25 08:12

BambooleanLogic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!