Rounding to n decimal places with typecasting
<logic>
Round “25.1462314” to 2 decimal places. Well you can do it at the snap of your fingers and tell me “25.15” and not “25.14”!
Glad that you have your good old <insert your age here> brain?
</logic>
Back to coding section. To round that number. I can simply use DecimalFormat class of Java API. But what if you aren’t suppose to use it? And you cant use Math class to round your figures either? Headache?
You will certainly say, I will check the 3rd digit after the decimal point and see if it is greater than 5, if it is, increment the 2nd digit after the decimal point by 1. Oops, forgot to tell you. No if-then-else statements either.
Alright, a programming trick I just uncovered. Spent me close to an hour pondering over it. I explain the trick step by step.
25.1462314 is my target and I want to round it off to 2 decimal places and becomes 25.15.
Firstly, multiply the target by 1000.
It becomes 25146.2314Secondly, get the integer section of it.
Becomes 25146Divide it by 10.
Becomes 2514.6Adds 0.5 to it.
Becomes 2515.1Get the integer section of it.
Becomes 2515Divide it by 100.
Becomes 25.15Ta Daaa~. You got the answer!
In coding sense it looks simply like
double roundOff = 25.1462314d;
int temp = (int) (roundOff * 1000);
roundOff = (double) temp / 10;
roundOff += 0.5d;
temp = (int) roundOff;
roundOff = (double) temp / 100;
if you don’t want it to round properly
double roundOff = 25.1462314d;
int temp = (int) (roundOff * 100);
roundOff = (int) temp / 100;
Well, good technique uncovered (by me). At least give me some credits for the hour of nutcracking thinking session I had.