*! version 2.1.0 2026-04-03

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: The "Cox Logic" and Precision

Stata expert Nicholas J. Cox has frequently cautioned users regarding the round() function, noting that decimal
fractions like 0.1 or 0.01 do not have exact binary representations. As Cox has observed, performing calculations
directly with integers is inherently more stable in digital computing because integers are represented exactly.

round_exact conforms to this reasoning but goes a step further. By scaling decimals into integers,
performing the rounding, and scaling back (round(val * 10^d) / 10^d), the command eliminates the
"trailing noise" found in standard functions.
This "back-and-forth" transformation ensures that the final decimal result matches the user's expectation
for exactness, enabling successful assert checks and exact, cross‑wave‑comparable results..

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 auto, clear

. round_exact price, d(2) 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

Date

April 3, 2026

Acknowledgment

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