## Tax Brackets

### January 26, 2021

My W-2 form came in the mail a few days ago, so a task about taxes is appropriate. Given the following tax brackets:

````income cap    tax rate`
`  \$ 10,000        0%`
`  \$ 30,000       10%`
`  \$100,000       25%`
`    more         40%````

For example, if your income is \$123,456, your tax is \$2,000 plus \$17,500 plus 40% of \$23,456 (or \$9,382.40), a total tax of \$28,882.40, or 23.4% of your income.

Your task is to write a program that calculates the amount of tax due for a given amount of income. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Pages: 1 2

### 5 Responses to “Tax Brackets”

1. James Smith said

Perl

```sub tax {
return ( ( \$_ >= 10_000  ? 2*(\$_-10_000)  : 0 )
+ ( \$_ >= 30_000  ? 3*(\$_-30_000)  : 0 )
+ ( \$_ >= 100_000 ? 3*(\$_-100_000) : 0 )
) / 20;
}
```
2. James Smith said

Forgot to say – the trick here is to only add the additional tax per bracket – so about 10K is 10%, above 30K is then (25-10)% = 15% and about 100K is then (40-25)% = 15% as well…

3. Kevin said

A solution in Racket:

```(define (taxbrk in (brk '(100000 30000 10000 0)) (tax '(0.40 0.25 0.10 0)) (out 0))
(cond
((zero? in) (display (real->decimal-string out)))
((> in (car brk)) (taxbrk (car brk) (cdr brk) (cdr tax) (+ out (* (car tax) (- in (car brk))))))
(else (taxbrk in (cdr brk) (cdr tax) out))))
```

Solution in use:

```> (taxbrk 123456)
28882.40
> (taxbrk 0)
0.00
> (taxbrk 10000)
0.00
> (taxbrk 30000)
2000.00
> (taxbrk 100000)
19500.00
> (taxbrk 100200)
19580.00
```
4. Daniel said

Here’s a solution in Python.

```from decimal import Decimal

def tax(income):
output = Decimal(0)
for threshold, rate in (100_000, '.40'), (30_000, '.25'), (10_000, '.10'):
if income >= threshold:
output += Decimal(rate) * (income - threshold)
income = threshold
return output

print(tax(123_456))
```

Output:

```28882.40
```
5. cagisw said

Solution in Java:

```public class TaxBrackets {

public static void main(String[] args) {

double income = 123456;
double calculateTax = calculateTax(income);
System.out.println(calculateTax);
}

private static double calculateTax(double income) {
double totalTax = 0;
double import1 = 10000;
double import2 = 30000;
double import3 = 100000;

if (income <= import1) {
}

if (income > import1 && income <= import2) {
income = income - import1;
totalTax = (income * 10) / 100;
}

if (income > import2 && income <= import3) {
income = income - import2;
totalTax = ((income * 25) / 100) + 2000;