BACKGROUND Early HIV diagnosis reduces morbidity, mortality, the probability of onward transmission, and their associated costs, but might increase cost because of earlier initiation of antiretroviral treatment (ART). We investigated this trade-off by estimating the cost-effectiveness of HIV screening in primary care. METHODS We modelled the effect of the four-times higher diagnosis rate observed in the intervention arm of the RHIVA2 randomised controlled trial done in Hackney, London (UK), a borough with high HIV prevalence (≥0·2% adult prevalence). We constructed a dynamic, compartmental model representing incidence of infection and the effect of screening for HIV in general practices in Hackney. We assessed cost-effectiveness of the RHIVA2 trial by fitting model diagnosis rates to the trial data, parameterising with epidemiological and behavioural data from the literature when required, using trial testing costs and projecting future costs of treatment. FINDINGS Over a 40 year time horizon, incremental cost-effectiveness ratios were £22 201 (95% credible interval 12 662-132 452) per quality-adjusted life-year (QALY) gained, £372 207 (268 162-1 903 385) per death averted, and £628 874 (434 902-4 740 724) per HIV transmission averted. Under this model scenario, with UK cost data, RHIVA2 would reach the upper National Institute for Health and Care Excellence cost-effectiveness threshold (about £30 000 per QALY gained) after 33 years. Scenarios using cost data from Canada (which indicate prolonged and even higher health-care costs for patients diagnosed late) suggest this threshold could be reached in as little as 13 years. INTERPRETATION Screening for HIV in primary care has important public health benefits as well as clinical benefits. We predict it to be cost-effective in the UK in the medium term. However, this intervention might be cost-effective far sooner, and even cost-saving, in settings where long-term health-care costs of late-diagnosed patients in high-prevalence regions are much higher (≥60%) than those of patients diagnosed earlier. Screening for HIV in primary care is cost-effective and should be promoted. FUNDING NHS City and Hackney, UK Department of Health, National Institute for Health Research Collaboration for Leadership in Applied Health Research and Care.