Then I started wrote that logic and thought of publishing it here.
Lets assume , The give amount is Rs. 640 and we need to calculate Tax for that.
Tax Slabs are given below
Tier Range | Percentage |
---|---|
1-300 | 10 |
301-600 | 20 |
601-1000 | 30 |
1001 and above | 40 |
The Tax Calculation for the given Amount Rs. 640 should be like this
Last / Third Tier up to 40 Rs Tax : 12
Total Tax Amount : 102
The method to do this operation given below
private static void calculate( double salary) {
TierRange[] tierRanges = new TierRange[] {
new TierRange(1, 300, 1.25), new TierRange(301, 600, 1.75), new TierRange(601, 1000, 2.25),
new TierRange(1001, 999999, 2.75),
};
double given = salary;
double amount = 0.0;
if (given == 0) {
amount = 0;
} else {
for (TierRange tierRange : tierRanges) {
int calcValue = 0;
if (given >= tierRange.low && given <= tierRange.high) {
calcValue = (given - tierRange.low) + 1;
amount += (calcValue * tierRange.value);
System.out.println(given+" "+calcValue+" "+amount+" "+(calcValue * tierRange.value));
break;
} else {
calcValue = (tierRange.high - tierRange.low) + 1;
amount += (calcValue * tierRange.value);
System.out.println(given+" "+calcValue+" "+amount+" "+(calcValue * tierRange.value));
}
}
}
TierRange is a class which contains 3 fields low , high and percentage .
The same can be done using a Stored Procedure also
BILL_ADMIN.TIER_TEMPLATE
The query to fetch the Tier Range given below
SELECT TIER_START , TIER_END , RATE_PU FROM BILL_ADMIN.TIER_TEMPLATE;
TIER_START --- Low Range
TIER_END ---- High Range
RATE_PU --- Rate Percentage
create or replace PROCEDURE BILLINGCALCPROC
IS
T_GIVEN NUMBER;
T_TIER_START NUMBER ;
T_TIER_END NUMBER;
T_RATE_PU NUMBER;
T_CALCVAL NUMBER;
T_BILL_ID VARCHAR2(30);
T_AMOUNT NUMBER;
CURSOR BILL_CALC
IS
SELECT TOTAL_UNIT, BILL_ID FROM BILL_ADMIN.MONTHLY_INVOICE ;
CURSOR TIER_RANGE
IS
SELECT TIER_START , TIER_END , RATE_PU FROM BILL_ADMIN.TIER_TEMPLATE;
BEGIN
OPEN BILL_CALC;
LOOP
FETCH BILL_CALC INTO T_GIVEN ,T_BILL_ID;
EXIT
WHEN BILL_CALC%NOTFOUND;
T_AMOUNT := 0;
IF (T_GIVEN=0) THEN
UPDATE BILL_ADMIN.MONTHLY_INVOICE SET AMOUNT = 0 WHERE BILL_ID = T_BILL_ID;
ELSE
OPEN TIER_RANGE;
LOOP
FETCH TIER_RANGE INTO T_TIER_START ,T_TIER_END, T_RATE_PU;
EXIT
WHEN TIER_RANGE%NOTFOUND;
T_CALCVAL := 0;
IF(T_GIVEN >= T_TIER_START AND T_GIVEN <= T_TIER_END) THEN
T_CALCVAL := (T_GIVEN - T_TIER_START ) +1;
T_AMOUNT := T_AMOUNT + (T_CALCVALT_RATE_PU);
UPDATE BILL_ADMIN.MONTHLY_INVOICE
SET AMOUNT = T_AMOUNT
WHERE BILL_ID = T_BILL_ID;
GOTO LOOP_END;
ELSE
T_CALCVAL := (T_TIER_END - T_TIER_START ) +1;
T_AMOUNT := T_AMOUNT + (T_CALCVALT_RATE_PU);
END IF;
END LOOP;
<>
CLOSE TIER_RANGE;
END IF;
END LOOP;
CLOSE BILL_CALC;
COMMIT;
END;
This is for the Refernce .