public static int round (int input, int places) { int factor = (int)java.lang.Math.pow(10, places); return (input / factor) * factor; }
Basically, this is what it is dividing the input by your factor, and then multiplying again. When dividing integers into languages ββsuch as Java, the rest of the division is discarded from the results.
edit: the code was faulty, fixed it. Also, java.lang.Math.pow is that you get 10 to the nth power, where n is the value of places . In the OP example, the number of places to consider is increased by one.
Rename: as indicated in the comments, the above will give you the word, i.e. the result of rounding down . If you do not want to always round down, you should also save the module in another variable. Like this:
int mod = input % factor;
If you want to always get the ceiling, i.e. round up , check if mod is equal. If so, leave it to that. Otherwise, add factor to the result.
int ceil = input + (mod == 0 ? 0 : factor);
If you want to round to the nearest, then get the word if mod less than factor / 2, or the ceiling otherwise.
Renan source share