문제

How to round up a decimal number to a whole number?

So for example when it is 1.25 rounds to 1 or -3.25 rounds to -3 etc

도움이 되었습니까?

해결책

if you want decimal part do this .

double value = 1.25;
int i = (int)value;

if you want to round value , do this

Math.round(value);

다른 팁

Use Math.round(float number) method http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round(float) if you want to round it. If you want to cut decimal part just cast it to int.

A small trick I've learned during the years is just adding the value 0.5 to the value you want to round. After you did that, you can round it to an integer.

It's a generic workaround, which will work with alot of programming languages.

I dont know much about Java, but I think you will find a round-Method in the API. The package should be Math.

Edit:\

To round UP you could just add 1 instead of the value 0.5.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top