Skip to main content

paycheck_utils/
lib.rs

1//! This library contains utility functions for calculating paycheck withholdings and net income given a hypothetical hourly wage and weekly working hours. The idea is pretty much like the "Sample Paycheck" tool found in the [Paycom](https://www.paycom.com/software/employee-self-service/) employee portal, but aimed at having a little more functionality and customization.
2//!
3//! The entire library was developed with the perspective of an hourly paid employee in mind, focusing on bi-weekly paychecks as the standard pay period to simulate how employees typically view and plan their income.
4//!
5//! The primary question this library aims to answer is: "Given an hourly wage and number of hours worked per week, what would my net paycheck be after taxes and deductions?"
6//!
7//! The secondary question this library aims to answer is: "Given a total monthly expenses amount and hourly wage, how many hours would I need to work to cover my expenses with "x" amount left over after taxes and deductions?" (this will be implemented in a future version).
8//!
9//! The library is structured into several modules:
10//! - `withholdings`: Contains functions to estimate federal tax withholdings, Social Security, and Medicare deductions.
11//! - `deductions`: Defines structures and functions for handling pre-tax and post-tax deductions.
12//! - `income`: Contains functions to calculate gross paycheck based on hourly wage and hours worked.
13//! - `expenses`: Defines structures and functions for managing monthly expenses.
14//! - `constants`: Contains tax and time related constants necessary for calculations.
15//! - `interaction`: Contains functions for interacting with the user to receive input for employment scenario.
16//! - `utils`: Contains utility functions for rounding and formatting output.
17
18pub mod constants;
19pub mod deductions;
20pub mod expenses;
21pub mod income;
22pub mod interaction;
23pub mod utils;
24pub mod withholdings;
25
26pub use crate::constants::*;
27pub use crate::deductions::*;
28pub use crate::expenses::*;
29pub use crate::income::*;
30pub use crate::interaction::*;
31pub use crate::utils::*;
32pub use crate::withholdings::*;
33
34/// Represents an employment scenario with hourly rate, hours worked per week, filing status, and deductions.
35/// Possible deductions avaialable are defined in the `deductions` module.
36///
37/// # Example
38/// ```
39/// use paycheck_utils::*;
40///
41/// let new_job_scenario = EmploymentScenario::new(
42///     30.0, // hourly rate
43///     40.0, // hours per week
44///     FilingStatus::Single, // filing status
45///     PreTaxDeductions::new(vec![
46///         PreTaxDeduction::Medical(Some(150.0)),
47///         PreTaxDeduction::Dental(Some(50.0)),
48///         PreTaxDeduction::Vision(Some(15.0)),
49///         PreTaxDeduction::Traditional401K(Some(200.0)),
50///     ]), // pre-tax deductions
51///     PostTaxDeductions::new(vec![PostTaxDeduction::Roth401K(Some(100.0))]), // post-tax deductions
52///     Expenses::new(vec![]) // expenses
53/// );
54/// ```
55///
56#[derive(Default, Debug)]
57pub struct EmploymentScenario {
58    pub hourly_rate: f32,
59    pub hours_per_week: f32,
60    pub filing_status: FilingStatus,
61    pub pretax_deductions: PreTaxDeductions,
62    pub posttax_deductions: PostTaxDeductions,
63    pub expenses: Expenses,
64}
65
66impl EmploymentScenario {
67    pub fn new(
68        hourly_rate: f32,
69        hours_per_week: f32,
70        filing_status: FilingStatus,
71        pretax_deductions: PreTaxDeductions,
72        posttax_deductions: PostTaxDeductions,
73        expenses: Expenses,
74    ) -> Self {
75        EmploymentScenario {
76            hourly_rate,
77            hours_per_week,
78            filing_status,
79            pretax_deductions,
80            posttax_deductions,
81            expenses,
82        }
83    }
84
85    /// Calculates the net paycheck based on the employment scenario's parameters.
86    /// The calculations consider gross income, pre-tax deductions, federal tax withholdings, Social Security, Medicare, and post-tax deductions.
87    /// The IRS defined constants used to make calculations (such as tax rates, thresholds and standard deductions) are defined in the `constants` module.
88    /// This IRS method and flow for calculating withholdings is based on the 2026 federal tax year guidelines and can be summarized as follows:
89    ///    1. Calculate gross paycheck on hourly rate and hours worked.
90    ///    2. Subtract pre-tax deductions from gross paycheck to get adjusted gross paycheck.
91    ///    3. Calculate federal tax withholdings based on annualized adjusted gross paycheck and filing status.
92    ///    4. Calculate Social Security and Medicare withholdings based on adjusted gross paycheck.
93    ///    5. Subtract federal tax withholdings, Social Security, Medicare, and post-tax deductions from adjusted gross paycheck to get net paycheck.
94    ///
95    /// # Example
96    /// ```
97    /// use paycheck_utils::*;
98    ///
99    /// let pretax_deductions = PreTaxDeductions::new(vec![
100    ///     PreTaxDeduction::Medical(Some(100.0)),
101    ///     PreTaxDeduction::Dental(Some(50.0)),
102    ///     PreTaxDeduction::Vision(Some(25.0)),
103    ///     PreTaxDeduction::Traditional401K(Some(200.0)),
104    ///     PreTaxDeduction::HSA(Some(150.0)),
105    /// ]); // total = 525.0
106    /// let posttax_deductions = PostTaxDeductions::new(vec![
107    ///     PostTaxDeduction::Roth401K(Some(100.0)),
108    ///     PostTaxDeduction::VoluntaryLife(Some(30.0)),
109    /// ]); // total = 130.0
110    /// let scenario = EmploymentScenario::new(
111    ///     25.0, // hourly rate
112    ///     45.0, // hours per week (bi-weekly paycheck = 90 hours [10 hours overtime])
113    ///     FilingStatus::Single, // single filing status for standard deduction
114    ///     pretax_deductions, // total = 525.0
115    ///     posttax_deductions, // total = 130.0
116    ///     Expenses::new(vec![
117    ///         Expense::Housing(Some(2000.0)),
118    ///         Expense::Energy(Some(300.0)),
119    ///     ]), // total = 2300.0
120    /// );
121    /// let net_paycheck = scenario.calculate_net_paycheck();
122    /// assert_eq!(net_paycheck, 1440.33);
123    ///
124    /// // Explanation of calculation:
125    /// // 1. Gross Paycheck: (25.0 * 80) + (25.0 * 10 * 1.5) = 2000.0 + 375.0 = 2375.0
126    /// // 2. Adjusted Gross Paycheck: 2375.0 - 525.0 = 1850.0  (after pre-tax deductions)
127    /// // 3. Federal Withholding (annualized AGP = 1850.0 * 26 = 48100.0): Using 2026 tax brackets for Single filer:
128    /// //    - 10% on first 12,400 = 12,400 * 0.10 = 1,240.0
129    /// //    - 12% on amount over 12,400 up to 50,400 = (48,100.0 - 12,400.0) * 0.12 = 4,290.0
130    /// //    - Total annual federal tax = 1,240.0 + 4,290.0 = 5,530.0
131    /// //    - Bi-weekly federal withholding = 5,530.0 / 26 = 212.69
132    /// // 4. Social Security Withholding: 1850.0 * 0.062 = 114.70
133    /// // 5. Medicare Withholding: 1850.0 * 0.0145 = 26.83
134    /// // 6. Post-Tax Deductions: 100.0 + 30.0 = 130.0
135    /// // 7. Total Deductions: 212.69 + 114.70 + 26.83 + 130.0 = 484.22
136    /// // 8. Net Paycheck: 1850.0 - 212.69 - 114.70 - 26.83 - 130.0 = 1440.33
137    /// ```
138    /// # Returns
139    /// An `f32` representing the calculated net paycheck amount.
140    ///
141    /// # Panics
142    /// This function does not explicitly panic, but it assumes that the input values (hourly rate, hours worked, deductions) are valid and reasonable.
143    ///
144    /// # Errors
145    /// This function does not return errors, but invalid input values may lead to incorrect calculations.
146    ///
147    /// # Notes
148    /// The calculations are based on the 2026 federal tax year guidelines and may need to be updated for future tax years.
149    pub fn calculate_net_paycheck(&self) -> f32 {
150        let mut gross_paycheck = determine_gross_paycheck(self.hourly_rate, self.hours_per_week);
151        let total_pretax = self.pretax_deductions.total_pretax_deductions();
152        gross_paycheck -= total_pretax;
153        let federal_withholding =
154            estimate_paycheck_federal_withholdings(gross_paycheck, self.filing_status);
155        let social_security = estimate_social_security_withholding(gross_paycheck);
156        let medicare = estimate_medicare_withholding(gross_paycheck);
157        let total_posttax = self.posttax_deductions.total_posttax_deductions();
158
159        round_2_decimals(
160            gross_paycheck - federal_withholding - social_security - medicare - total_posttax,
161        )
162    }
163
164    /// Compares the total monthly expenses to the calculated monthly net income.
165    /// Returns a tuple containing the monthly net income, total monthly expenses, and the difference between the two.
166    /// # Example
167    /// ```
168    /// // This example uses the same data as the `calculate_net_paycheck` example to demonstrate the comparison.
169    ///
170    /// use paycheck_utils::*;
171    ///
172    /// let pretax_deductions = PreTaxDeductions::new(vec![
173    ///     PreTaxDeduction::Medical(Some(100.0)),
174    ///     PreTaxDeduction::Dental(Some(50.0)),
175    ///     PreTaxDeduction::Vision(Some(25.0)),
176    ///     PreTaxDeduction::Traditional401K(Some(200.0)),
177    ///     PreTaxDeduction::HSA(Some(150.0)),
178    /// ]); // total = 525.0
179    /// let posttax_deductions = PostTaxDeductions::new(vec![
180    ///     PostTaxDeduction::Roth401K(Some(100.0)),
181    ///     PostTaxDeduction::VoluntaryLife(Some(30.0)),
182    /// ]); // total = 130.0
183    /// let expenses = Expenses::new(vec![
184    ///     Expense::Housing(Some(1500.0)),
185    ///     Expense::Energy(Some(200.0)),
186    ///     Expense::Water(Some(50.0)),
187    ///     Expense::Groceries(Some(400.0)),
188    ///     Expense::Phone(Some(80.0)),
189    ///     Expense::Internet(Some(60.0)),
190    /// ]); // total = 2290.0
191    /// let scenario = EmploymentScenario::new(
192    ///     25.0, // hourly rate
193    ///     45.0, // hours per week
194    ///     FilingStatus::Single, // filing status
195    ///     pretax_deductions,
196    ///     posttax_deductions,
197    ///     expenses,
198    /// );
199    /// let (monthly_net_income, total_monthly_expenses, difference) = scenario.compare_monthly_expenses_to_monthly_income();
200    /// assert_eq!(monthly_net_income, 2880.66);
201    /// assert_eq!(total_monthly_expenses, 2290.0);
202    /// assert_eq!(difference, 590.66);
203    /// ```
204    /// # Returns
205    /// A tuple containing:
206    /// - `f32`: Monthly net income
207    /// - `f32`: Total monthly expenses
208    /// - `f32`: Difference between monthly net income and total monthly expenses
209    pub fn compare_monthly_expenses_to_monthly_income(&self) -> (f32, f32, f32) {
210        let monthly_net_income = self.calculate_net_paycheck() * 2.0;
211        let total_monthly_expenses = self.expenses.total_monthly_expenses();
212        (
213            round_2_decimals(monthly_net_income),
214            round_2_decimals(total_monthly_expenses),
215            round_2_decimals(monthly_net_income - total_monthly_expenses),
216        )
217    }
218}
219
220// UNIT TEST FOR LIBRARY
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    #[test]
226    fn test_calculate_net_paycheck() {
227        let pretax_deductions = PreTaxDeductions::new(vec![
228            PreTaxDeduction::Medical(Some(100.0)),
229            PreTaxDeduction::Dental(Some(50.0)),
230            PreTaxDeduction::Vision(Some(25.0)),
231            PreTaxDeduction::Traditional401K(Some(200.0)),
232            PreTaxDeduction::HSA(Some(150.0)),
233        ]);
234        let posttax_deductions = PostTaxDeductions::new(vec![
235            PostTaxDeduction::Roth401K(Some(100.0)),
236            PostTaxDeduction::VoluntaryLife(Some(30.0)),
237        ]);
238        let expenses = Expenses::new(vec![
239            Expense::Housing(Some(2000.0)),
240            Expense::Energy(Some(200.0)),
241            Expense::Water(Some(50.0)),
242            Expense::Internet(Some(60.0)),
243            Expense::Phone(Some(80.0)),
244            Expense::Vehicle(Some(300.0)),
245            Expense::VehicleInsurance(Some(150.0)),
246            Expense::VehicleGas(Some(100.0)),
247            Expense::Groceries(Some(400.0)),
248        ]);
249        let scenario = EmploymentScenario::new(
250            25.0,
251            45.0,
252            FilingStatus::Single,
253            pretax_deductions,
254            posttax_deductions,
255            expenses,
256        );
257        let net_paycheck = scenario.calculate_net_paycheck();
258        assert_eq!(net_paycheck, 1440.33);
259    }
260
261    #[test]
262    fn test_compare_monthly_expenses_to_monthly_income() {
263        let pretax_deductions = PreTaxDeductions::new(vec![
264            PreTaxDeduction::Medical(Some(100.0)),
265            PreTaxDeduction::Dental(Some(50.0)),
266            PreTaxDeduction::Vision(Some(25.0)),
267            PreTaxDeduction::Traditional401K(Some(200.0)),
268            PreTaxDeduction::HSA(Some(150.0)),
269        ]);
270        let posttax_deductions = PostTaxDeductions::new(vec![
271            PostTaxDeduction::Roth401K(Some(100.0)),
272            PostTaxDeduction::VoluntaryLife(Some(30.0)),
273        ]);
274        let expenses = Expenses::new(vec![
275            Expense::Housing(Some(1500.0)),
276            Expense::Energy(Some(200.0)),
277            Expense::Water(Some(50.0)),
278            Expense::Groceries(Some(400.0)),
279            Expense::Phone(Some(80.0)),
280            Expense::Internet(Some(60.0)),
281        ]);
282        let scenario = EmploymentScenario::new(
283            25.0,
284            45.0,
285            FilingStatus::Single,
286            pretax_deductions,
287            posttax_deductions,
288            expenses,
289        );
290        let (monthly_net_income, total_monthly_expenses, difference) =
291            scenario.compare_monthly_expenses_to_monthly_income();
292        assert_eq!(monthly_net_income, 2880.66);
293        assert_eq!(total_monthly_expenses, 2290.0);
294        assert_eq!(difference, 590.66);
295    }
296}