For instance, I have integers, i.e. 450. I want to get 1/100 of the number N. In this case it should be 4.5, which will rounded to 5.
int i = 450;
int round = Math.round(i/450)?
When the i varies, is this safe always?
For instance, I have integers, i.e. 450. I want to get 1/100 of the number N. In this case it should be 4.5, which will rounded to 5.
int i = 450;
int round = Math.round(i/450)?
When the i varies, is this safe always?
i/450
will do an integer division before the result gets passed into Math.round
and you won't get what you expected. Even then you got ~1/450 of the value, not 0.01 of it. You need
(int)Math.round(i/100.0);
However you can do rounding with just integer math like either of these
int round = (i + 50)/100; // i + 99 for ceiling
int round = (i - 1)/100 + 1;
int round = i/100 + (i % 100 < 50 ? 0 : 1);
For more information read Rounding integer division (instead of truncating)
See also
These are about ceiling function but you can get the idea
For it to work no matter numerator or denominator, then
BigDecimal.valueOf(450).divide(BigDecimal.valueOf(100),RoundingMode.HALF_UP);
Another way could be like
BigDecimal.valueOf(450,2).setScale(0, RoundingMode.HALF_UP);
You can convert back to int
using .intValue()
That would only make sense of course when you are dealing with exact decimal math most of the time until the very end, like would be the case for financial applications.
I "think" this might be what you are looking for:
float i = 450;
int round = Math.round(i/100);
System.out.println(round);//prints 5
Division with int always rounds down so when i is an int, the expression i/100 returns 4 when i is between 400 and 499.
Alternately, you could cast to float:
int i = 450;
int round = Math.round((float)i/100);
System.out.println(round);//prints 5