Documentation
¶
Overview ¶
Package vnsalary provides an exact Gross-to-Net and Net-to-Gross salary and personal income tax (PIT / Thuế TNCN) calculator according to Vietnamese labor and taxation regulations.
The library determines statutory parameters based on the income payment date (Date): taxable income from salaries is determined when the income is paid (Law on PIT No. 109/2025/QH15, Article 8.3; previously Circular 111/2013/TT-BTC, Article 8.2.b).
All monetary values are represented as integer Vietnamese Dong (VND int64) with half-up integer rounding independently applied to mandatory insurance items and progressive tax brackets. No floating-point arithmetic (zero float64) and zero external dependencies (Go Standard Library only).
Index ¶
Examples ¶
Constants ¶
const ( // WarnOvertimeTaxedBeforeExemption: before tax period 2026 only the part of // overtime pay above normal-hours pay was exempt (Circular 111/2013/TT-BTC // Art. 3.1.i). The library cannot split Extras.Overtime, so it taxes all of // it; put the exempt part in Extras.OtherExempt instead. WarnOvertimeTaxedBeforeExemption = "overtime_taxed_before_2026" // WarnMealCapUnverified: the meal allowance cap for this payment date could // not be confirmed from a legal text; the policy's cap is applied. WarnMealCapUnverified = "meal_cap_unverified" // WarnInsuranceSalaryIncludesAllowances: InsuranceBase is nil, so MealCash // and OtherExempt are included in the insurance salary. Set InsuranceBase if // the employment contract excludes them. WarnInsuranceSalaryIncludesAllowances = "insurance_salary_includes_allowances" )
Warning codes for Options.Extras.
const WarnInsuranceSalaryBelowRegionalMinimum = "insurance_salary_below_regional_minimum"
WarnInsuranceSalaryBelowRegionalMinimum is reported when the salary used for insurance (InsuranceBase, or gross when InsuranceBase is nil) is positive but below the regional minimum wage. A full-time employee must be paid at least that minimum (Labour Code 2019, Art. 90.2), so a lower insurance salary usually means a part-time contract or an input mistake. It is a warning, not an error: the legal floor for the social insurance salary itself is the reference level (Law on Social Insurance 41/2024/QH15, Art. 31.1), which is lower than the regional minimum.
Variables ¶
var ( // ErrInvalidAmount indicates that a negative amount was supplied for gross or net salary. ErrInvalidAmount = errors.New("vnsalary: amount must be non-negative") // ErrAmountTooLarge indicates that an amount exceeds the supported maximum (100 trillion VND). ErrAmountTooLarge = errors.New("vnsalary: amount exceeds supported maximum (100,000,000,000,000 VND)") // ErrInvalidDependents indicates that the dependents count is out of range [0, 50]. ErrInvalidDependents = errors.New("vnsalary: dependents count must be between 0 and 50") // ErrInvalidRegion indicates that the minimum wage region is outside [1, 4]. ErrInvalidRegion = errors.New("vnsalary: region must be between 1 and 4") // ErrDateOutOfRange indicates that the effective date is prior to July 01, 2024. ErrDateOutOfRange = errors.New("vnsalary: date must be on or after 2024-07-01") // ErrDateZero indicates that a zero time value was provided for the payment date. ErrDateZero = errors.New("vnsalary: date cannot be zero") // ErrExtrasExceedGross indicates that Options.Extras add up to more than gross; // gross is the total paid in the month and must include them. ErrExtrasExceedGross = errors.New("vnsalary: extras exceed gross (gross must include them)") // ErrInsuranceExceedsGross indicates that the mandatory employee insurance contribution exceeds the gross salary. ErrInsuranceExceedsGross = errors.New("vnsalary: insurance contribution exceeds gross salary") // ErrNetUnreachable indicates that no integer gross amount maps to this exact net salary due to half-up discretization. ErrNetUnreachable = errors.New("vnsalary: net salary is unreachable due to integer rounding") )
Functions ¶
This section is empty.
Types ¶
type BracketLine ¶
type BracketLine struct {
Bracket int `json:"bracket"` // Tax bracket index (1, 2, ...)
TaxablePart VND `json:"taxable_part"` // Income portion assessed within this bracket
RatePercent int `json:"rate_percent"` // Tax rate percentage (5, 10, 15, ...)
Tax VND `json:"tax"` // Tax amount accrued at this bracket
}
BracketLine details personal income tax paid at a specific progressive bracket.
type Deductions ¶
type Deductions struct {
Personal VND `json:"personal"` // Taxpayer personal deduction (giảm trừ bản thân)
Dependents VND `json:"dependents"` // Qualifying dependents deduction (giảm trừ người phụ thuộc)
Total VND `json:"total"` // Total deduction amount
}
Deductions itemizes personal and family tax relief deductions (giảm trừ gia cảnh).
type EmployerCost ¶
type EmployerCost struct {
Social VND `json:"social"` // Social insurance (BHXH) 17.5% (14% pension/death, 3% sickness/maternity, 0.5% occupational accident)
Health VND `json:"health"` // Health insurance (BHYT) 3%
Unemployment VND `json:"unemployment"` // Unemployment insurance (BHTN) 1%
TotalInsurance VND `json:"total_insurance"` // Total employer contribution (21.5%)
TotalCost VND `json:"total_cost"` // Total employer cost = Gross + TotalInsurance
}
EmployerCost itemizes statutory employer contributions and total company expenditure.
type ExemptIncome ¶ added in v0.3.0
type ExemptIncome struct {
Overtime VND `json:"overtime"`
Meal VND `json:"meal"`
Other VND `json:"other"`
Total VND `json:"total"`
}
ExemptIncome itemizes the parts of gross excluded from taxable income (thu nhập không tính thuế).
type Extras ¶ added in v0.3.0
type Extras struct {
Overtime VND // Overtime and night-work pay within the legal hour limits; fully tax-exempt from tax period 2026 (pay for hours beyond the limits belongs in gross only)
MealCash VND // Cash meal allowance; tax-exempt up to Policy.MealCashCap
OtherExempt VND // Other allowances exempt under the employer's regulation (phone, uniform, travel...); the caller is responsible for their limits
Bonus VND // Bonus paid this month; taxable, outside the insurance salary
}
Extras are amounts already included in gross (gross is the total paid in the month) that the law treats differently from base salary. The zero value reproduces the calculation of earlier versions.
When InsuranceBase is nil, the insurance salary is gross minus Overtime and Bonus: both vary from month to month, so they are outside the salary "paid regularly and stably" (Law on Social Insurance 41/2024/QH15 Art. 31.1.b). MealCash and OtherExempt stay in the insurance salary; set InsuranceBase if the employment contract excludes them.
type Insurance ¶
type Insurance struct {
Social VND `json:"social"` // Social insurance (BHXH) 8%
Health VND `json:"health"` // Health insurance (BHYT) 1.5%
Unemployment VND `json:"unemployment"` // Unemployment insurance (BHTN) 1%
Total VND `json:"total"` // Total employee insurance contribution
}
Insurance itemizes mandatory employee contributions.
type Options ¶
type Options struct {
InsuranceBase *VND // nil = based on gross salary; non-nil = contractual insurance salary (lương đóng bảo hiểm)
Dependents int // Qualifying dependents count (0..50) (số người phụ thuộc)
Region Region // Statutory minimum wage region (1..4) (vùng lương tối thiểu)
Date time.Time // Salary payment date; selects the policy in force (cash basis, Law on PIT 109/2025/QH15 Art. 8.3)
Extras Extras // Parts of gross treated differently from base salary; zero value = none
}
Options specifies optional calculation parameters.
type Policy ¶
type Policy struct {
EffectiveFrom time.Time
Ref PolicyRef
// Base salary (lương cơ sở / mức tham chiếu) and statutory ceiling for social & health insurance (20 x base salary)
BaseSalary VND
MaxSocialHealthSalary VND
// Regional minimum wages for Regions I, II, III, IV (index 1..4) used to cap unemployment insurance (20 x regional min)
RegionalMinSalaries [5]VND
// Monthly personal family deductions (giảm trừ gia cảnh)
PersonalDeduction VND // Personal taxpayer deduction (giảm trừ bản thân)
DependentDeduction VND // Deduction per qualifying dependent (giảm trừ người phụ thuộc)
// Progressive PIT schedule (biểu thuế lũy tiến từng phần)
Brackets []TaxBracket
// Income excluded from PIT (thu nhập không tính thuế), see Extras.
MealCashCap VND // Cash meal allowance excluded from taxable income up to this amount per month
MealCashCapVerified bool // False when the cap for this period could not be confirmed from a legal text
OvertimeFullyExempt bool // Overtime and night-work pay within the legal limits is fully excluded (from tax period 2026)
}
Policy contains all statutory parameters effective for a given period.
func PolicyAt ¶
PolicyAt returns the statutory policy parameter set effective at the given payment date. The returned value is an independent deep copy: modifying it will not affect any subsequent calculations. Returns ErrDateOutOfRange if date is prior to July 01, 2024.
func (Policy) MaxUnemploymentSalary ¶
MaxUnemploymentSalary returns the statutory cap for unemployment insurance (20 x regional minimum wage).
func (Policy) RegionalMinSalary ¶
RegionalMinSalary returns the statutory minimum wage for the specified region.
type PolicyRef ¶
type PolicyRef struct {
EffectiveFrom string `json:"effective_from"`
Description string `json:"description"` // Description in English
DescriptionVI string `json:"description_vi"` // Description in Vietnamese (mô tả tiếng Việt)
Sources []string `json:"sources"` // Official statutory legal documents in Vietnamese
}
PolicyRef provides references to statutory decrees and enacted legislation.
type Region ¶
type Region int
Region represents the statutory minimum wage region (Vùng lương tối thiểu: 1, 2, 3, 4).
type Result ¶
type Result struct {
Gross VND `json:"gross"`
Net VND `json:"net"`
Insurance Insurance `json:"insurance"`
TaxableIncome VND `json:"taxable_income"` // Total taxable income (thu nhập chịu thuế)
AssessableIncome VND `json:"assessable_income"` // Income assessed for PIT after insurance and deductions (thu nhập tính thuế)
Deductions Deductions `json:"deductions"`
Tax VND `json:"tax"`
Brackets []BracketLine `json:"brackets"`
Employer EmployerCost `json:"employer"`
Policy PolicyRef `json:"policy"`
Exempt *ExemptIncome `json:"exempt,omitempty"` // Exempt parts of gross; set only when Options.Extras is used
BonusTax VND `json:"bonus_tax,omitempty"` // Tax caused by Extras.Bonus: tax with the bonus minus tax without it
Warnings []Warning `json:"warnings,omitempty"` // Inputs computed as given but worth checking; never change amounts
}
Result holds the comprehensive breakdown of a salary calculation.
func GrossToNet ¶
GrossToNet converts Gross salary to Net take-home pay and itemizes all deductions.
Example ¶
package main
import (
"fmt"
"time"
"github.com/HuynhNhatKhanh/vnsalary"
)
func main() {
opts := vnsalary.Options{
Dependents: 1,
Region: vnsalary.Region1,
Date: time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC),
}
res, err := vnsalary.GrossToNet(35_000_000, opts)
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("Gross: %d VND\n", res.Gross)
fmt.Printf("BHXH (8%%): %d VND\n", res.Insurance.Social)
fmt.Printf("BHYT (1.5%%): %d VND\n", res.Insurance.Health)
fmt.Printf("BHTN (1%%): %d VND\n", res.Insurance.Unemployment)
fmt.Printf("Total Insurance: %d VND\n", res.Insurance.Total)
fmt.Printf("Tax: %d VND\n", res.Tax)
fmt.Printf("Net: %d VND\n", res.Net)
}
Output: Gross: 35000000 VND BHXH (8%): 2800000 VND BHYT (1.5%): 525000 VND BHTN (1%): 350000 VND Total Insurance: 3675000 VND Tax: 481250 VND Net: 30843750 VND
func NetToGross ¶
NetToGross solves the minimum integer Gross salary that yields the exact Net salary.
Step 1: Analytical piecewise linear interpolation on the interval [bps[i], bps[i+1]] containing net to derive gApprox. Step 2: Ascending scan within +/- searchRadius (50 VND) around gApprox; the first match is then extended downward to the smallest gross with the same net. Step 3 (Fallback): Monotonic binary search on [segmentLow, segmentHigh] to guarantee complete coverage.
Example ¶
package main
import (
"fmt"
"time"
"github.com/HuynhNhatKhanh/vnsalary"
)
func main() {
opts := vnsalary.Options{
Dependents: 1,
Region: vnsalary.Region1,
Date: time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC),
}
res, err := vnsalary.NetToGross(30_843_750, opts)
if err != nil {
fmt.Printf("error: %v\n", err)
return
}
fmt.Printf("Net: %d VND -> Gross: %d VND\n", res.Net, res.Gross)
}
Output: Net: 30843750 VND -> Gross: 35000000 VND
type TaxBracket ¶
type TaxBracket struct {
Limit VND // Upper limit of assessable income in this bracket (e.g. 5,000,000 VND; math.MaxInt64 for the top bracket)
RateNumerator int64 // Tax rate numerator (e.g. 5)
RateDenom int64 // Tax rate denominator (e.g. 100)
}
TaxBracket represents a single bracket in the progressive personal income tax schedule.
type VND ¶
type VND int64
VND is an amount in Vietnamese Dong as a whole number. Salaries are non-negative; differences between two results (for example in a policy comparison) may be negative.
const ( // MaxGross is the maximum supported salary amount (100 trillion VND) to guard against int64 overflow. MaxGross VND = 100_000_000_000_000 // MaxDependents is the maximum allowed number of dependents. MaxDependents = 50 )
func RoundToThousand ¶
RoundToThousand rounds a non-negative VND amount to the nearest thousand (1,000 VND) half-up. Convenient for payroll systems with cash-disbursement rounding policies.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
vnsalary
command
Command vnsalary converts Vietnamese gross and net salaries from the command line, using the github.com/HuynhNhatKhanh/vnsalary library.
|
Command vnsalary converts Vietnamese gross and net salaries from the command line, using the github.com/HuynhNhatKhanh/vnsalary library. |