Pergunta

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

Foi útil?

Solução

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);

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top