I am working on a function where I am calculating meter units to amount. Rules for meter calcualtions are :
- Minimum fare on 1.6km amt – 12/-
- Subsequent 1 km amt – 7/-
- 25% additional fare for journey for midnight
The function I have written is :
public static void CalculateAutoFare(int kmIndex) {
double fare = 12.00;
double night = 15.00;
double subseIncre = 1.50;
double nightIncre = 0.25;
int j=0;
for (int i=1; i <= kmIndex; i++) {
if (i == 3 || j == 4) {
fare += 1.00f;
j =0;
}
else {
fare += subseIncre;
j++;
}
fare = Math.round(fare*2f)/2f;
double extra = ((double) fare * nightIncre);
night = fare + extra;
night = Math.round(night*2f)/2f;
System.out.println("I = " + i + " Fare = " + fare + " Night = " + night + " 25%Extra = " + extra);
}
System.out.println("Day = " + fare + " Night = " + night);
}
kmIndex is the index of km. Meter readings are as 1.00, 1.10, 1.20, 1.30…1.90, 2.00…. Thus kmIndex for 1.00 = 0, 1.10 = 1, 1.20 – 3 and so on.
Results that I get as per code and should be is mentioned below :
I have worked till 4.00 and where the results are not right are declared undet Should Be of relevant to Day or Night.
I worked a lot on this but couldn’t get results as expected. If I try to correct 1 thing then other gets wrong or doesn’t give expected results. Can anyone help me out with this. Have spent almost whole day trying to solve this.
I’ve analyzed the worksheet and I haven’t found a formula that gives the results shown there. It seems that some values have some rounding differences. I’ve realized that only the values with 25 or 75 cents were different. For example, you calculated 18,5 and it should be 19 (the result was 18,75 and you rounded down to 18,5, but it should be rounded up to 19).
So, if you don’t have the original formula that was used to create the table, I think the only way to be sure that the results will match the worksheet is to hardcode it. It’s not an elegant solution, but it guarantees the correct result.