*! version 2.7.0 2026-04-08

Title

round_exact -- Exact decimal rounding using integer transformation to bypass floating-point noise.

Syntax

round_exact varname [if] [in] , d(integer) [options]

round_exact # , d(integer)

Main
* d(integer) specify the number of decimal places for rounding.

generate(newvar) create a new variable to store the rounded values.

replace overwrite the existing variable with rounded values.

* d(integer) is required.

Description

round_exact addresses the common issue of floating-point precision errors in Stata's built-in round(x, unit) function.
Standard rounding often leaves "noise" in binary representation (e.g., round(0.3, 0.1) resulting in 0.30000000000000004), which
causes logical assertions to fail.

This command implements the formula: round(val * 10^d) / 10^d. By transforming the value into an integer before rounding,
it avoids the precision errors introduced by fractional units.

Remarks: Precision and Binary Representation

As frequently noted by Nicholas J. Cox, decimal fractions like 0.1 or 0.01 often lack exact binary
representations, leading to unexpected "noise" in calculations. For a comprehensive overview of rounding
logic and its implications in Stata, see: Cox, N. J. 2018. Speaking Stata: From rounding to binning.
Stata Journal 18: 741-754.

A foundational discussion of the architectural hurdles of digital computing was provided by
William Gould, President and Architect of Stata. See: Gould, William. 2006.
Mata Matters: Precision. Stata Journal 6: 550-560.

Performing calculations with integers is inherently more stable because integers are represented
exactly. round_exact follows this logic by scaling decimals into integers, performing the
rounding, and then scaling back. This "back-and-forth" transformation ensures that the final decimal
result matches the user's expectation for exactness, enabling successful assert checks and
consistent results across comparative data analysis.

Examples

Rounding a literal for display or scalar return:

. round_exact 0.3, d(1)

. assert r(val) == 0.3

Rounding a variable in a dataset:

. sysuse nlsw88, clear

. round_exact wage, d(4) replace

Creating a new rounded variable:

. round_exact gear_ratio, d(1) generate(gr_rounded)

. list gear_ratio gr_rounded

Author

Anne Fengyan Shi, Pew Research Center

Support: email AShi@pewresearch.org

Acknowledgment

This program was developed to address precision hurdles in longitudinal fraction arithmetic and comparative data analysis.