Reputation: 73
When i try cast double to int. My variable "check" is always equals zero. But if i do it in psvm it works. If i do it in class check is always equals zero. How can i fix this problem? I try use Double and Integer for cast it doesn't work too.
I use java 11 on Ubuntu 18.
public class Round {
public int round (double value) {
return (value > 0) ? roundPositiveNubmer(value) : roundNegativeNumber(value);
}
private int roundPositiveNubmer(double value) {
int result;
double checkD = value * 10 % 10;
int check = (int) checkD;
if (check > 5) {
value++;
result = (int) value;
} else {
result = (int) value;
}
return result;
}
private int roundNegativeNumber(double value) {
int result;
double checkD = value * 10 % 10;
int check = (int) checkD;
if (check > -5 && check < 0) {
value--;
result = (int) value;
} else {
result = (int) value;
}
return result;
}
}
When i try to round 23.6. I've got 23 but must 24.
Upvotes: 0
Views: 633
Reputation: 86149
Your code works nicely in the positive case, as JB Nizet already hinted in a comment.
The trouble is with the negative case. round(-23.6)
yields -23, not -24. It is caused by this line:
if (check > -5 && check < 0) {
In the -23.6 case check
is -6, which is less than -5. I think you want the simpler:
if (check < -5) {
Now -23.6 is rounded to -24. -23.5 is still rounded to -23. If you wanted -24 in this case too:
if (check <= -5) {
You may also want to consider whether you wanted >=
in the positive case.
Sourabh Bhat is right in the comment too: You are reinventing the wheel. Math.round()
already does the job that your rounding method is doing. So if you are coding this as an exercise, fine, you’re learning, that’s always good. For production code you should prefer to use the existing built-in library method instead.
int rounded = Math.toIntExact(Math.round(-23.6));
System.out.println("Rounded: " + rounded);
Rounded: -24
Upvotes: 2