Conceptcore
Rounding modes
Also called rounding mode, rounding rule, tie-breaking rule, round half to even, bankers' rounding, round half up, round half away from zero, round toward zero, truncation, floor, ceiling, directed rounding.
A rounding mode says which nearby value replaces a number that has too many digits. Modes differ in their direction and in how they break ties, and the default differs between languages and functions.
- Applies to
- core-languages
Idea
A number often has more digits than the result can keep. A sum of money has more than two decimal places, an exact quotient has more bits than a double, and a measurement must become an integer. A rounding mode is the rule that picks the value to keep.
There are two kinds of rules.
- Directed rounding always moves the same way: down (floor, toward minus infinity), up (ceiling, toward plus infinity), toward zero (truncation), or away from zero.1
- Rounding to nearest picks the closest value. It needs a second rule for a tie, a value exactly halfway between two candidates. The common tie rules are half up, half away from zero, and half to even.1
import math
from decimal import ROUND_HALF_UP, Decimal
def half_away(x):
return int(Decimal(x).quantize(Decimal(1), rounding=ROUND_HALF_UP))
print(f"{'x':>5} {'even':>5} {'away':>5} {'floor':>5} {'ceil':>5} {'trunc':>5}")
for x in [0.5, 1.5, 2.5, -0.5, -1.5, -2.5]:
print(f"{x:5} {round(x):5} {half_away(x):5} {math.floor(x):5} {math.ceil(x):5} {math.trunc(x):5}")
x even away floor ceil trunc
0.5 0 1 0 1 0
1.5 2 2 1 2 1
2.5 2 3 2 3 2
-0.5 0 -1 -1 0 0
-1.5 -2 -2 -2 -1 -1
-2.5 -2 -3 -3 -2 -2
Python's round uses half to even, so round(0.5) and round(2.5) go to the even neighbour.2 Python's ROUND_HALF_UP in the decimal module means "ties going away from zero".3 The names of the modes are not the same in every library.
How it works
The tie rules
Every round-to-nearest rule gives the same result except at a tie. The rules differ in where a tie goes.1
- Half up (toward plus infinity): 2.5 becomes 3 and -2.5 becomes -2.
- Half away from zero: 2.5 becomes 3 and -2.5 becomes -3. Wikipedia calls this rule "commonly taught and used".1
- Half to even: a tie goes to the even neighbour. "Thus, for example, 23.5 becomes 24, as does 24.5".1 It is also called convergent rounding, statistician's rounding, Gaussian rounding or bankers' rounding.1
- Half down and half to odd are two more tie rules.1
The rounding modes of IEEE 754
Every IEEE 754 operation computes the exact result and then rounds it to the format.4 The rule for that step is the rounding mode. IEEE 754 "defines five rounding rules".5
| Rule | +11.5 | +12.5 | -11.5 | -12.5 |
|---|---|---|---|---|
| to nearest, ties to even | +12 | +12 | -12 | -12 |
| to nearest, ties away from zero | +12 | +13 | -12 | -13 |
| toward 0 | +11 | +12 | -11 | -12 |
| toward +infinity | +12 | +13 | -11 | -12 |
| toward -infinity | +11 | +12 | -12 | -13 |
The table follows the IEEE 754 article.5 "Round to nearest, ties to even" is the default for binary floating point, and ties away from zero "is only required for decimal implementations".5 Goldberg: "By default, rounding means round toward nearest. The standard requires that three other rounding modes be provided".4
Most programs never change the mode. C gives access to it through <fenv.h>: fegetround and fesetround with the macros FE_TONEAREST, FE_UPWARD, FE_DOWNWARD and FE_TOWARDZERO.6
Why half to even
A rule that always sends ties the same way adds a small bias. Goldberg shows it with three decimal digits, x = 1.00 and y = -0.555. Under round half up, the steps x - y and then + y give 1.56, 1.01, 1.57, 1.02, and so on: "each successive value of xn increases by .01". "Under round to even, xn is always 1.00."4 Goldberg's conclusion: "when using the round up rule, computations can gradually drift upward, whereas when using round to even the theorem says this cannot happen."4
With half to even, the errors of many roundings tend to cancel. Wikipedia says the error of a sum then grows "in proportion to the square root of the number of operations rather than linearly".1
Directed rounding and interval arithmetic
The directed modes give bounds. Goldberg: "One application of rounding modes occurs in interval arithmetic". The sum of two intervals takes its lower end rounded toward minus infinity and its upper end rounded toward plus infinity, so the exact result is inside the interval.4 Round toward minus infinity also makes conversion to an integer the floor function, and round toward plus infinity makes it the ceiling.4
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript numbers are JavaScript numbers, with Math.round, Math.floor, Math.ceil and Math.trunc. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has round, roundToInt, floor, ceil and truncate for Double, and java.math.RoundingMode for BigDecimal on the JVM. No example file exists because kotlinc is not installed. |
| SQL | Native | PostgreSQL round breaks ties away from zero for numeric, and for double precision the tie rule depends on the platform. No example file exists. |
| Bash | Absent | Bash arithmetic expansion has integers only, so there is no rounding of fractions and no rounding mode to set. No example file exists. |
| PowerShell | Native | PowerShell [math]::Round is System.Math.Round, with half to even by default and the MidpointRounding values. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no arithmetic. |
| CSS | Native | CSS round() takes the strategy nearest, up, down or to-zero, and nearest rounds a tie up, as JavaScript Math.round does. No example file exists. |
| Regular expressions | Does not apply | A pattern matches text and does no arithmetic. |
| Language | Verdict | Form |
|---|---|---|
| Python | native | round (half to even), math.floor, math.ceil, math.trunc, decimal modes ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_DOWN and others |
| JavaScript | native | Math.round (half toward plus infinity), Math.floor, Math.ceil, Math.trunc |
| TypeScript | native | as JavaScript |
| Java | native | Math.round (half toward plus infinity), Math.rint (half to even), java.math.RoundingMode |
| C | native | round, rint, floor, ceil, trunc, and fesetround |
| C++ | native | std::round, std::rint, std::fesetround |
| C# | native | Math.Round (half to even by default), MidpointRounding |
| Go | native | math.Round (half away from zero), math.RoundToEven, math.Floor, math.Ceil, math.Trunc |
| Rust | native | round (half away from zero), round_ties_even, floor, ceil, trunc |
| Kotlin | native | round, roundToInt, java.math.RoundingMode |
| PowerShell | native | [math]::Round with MidpointRounding |
| Bash | absent | integer arithmetic only |
| SQL | native | PostgreSQL round, trunc, floor, ceil |
| Regex | n/a | no arithmetic |
| HTML | n/a | no arithmetic |
| CSS | native | round() with nearest, up, down or to-zero |
The function called "round" has a different tie rule in each language. This is the main trap.
- Python
roundrounds to the closest multiple of the power of ten, and "if two multiples are equally close, rounding is done toward the even choice".2 Thedecimalmodule has eight modes and usesROUND_HALF_EVENin its default context.3 - JavaScript
Math.roundrounds a fraction of exactly 0.5 "to the next integer in the direction of +∞". MDN notes that this "differs from many languages' round() functions, which often round half-increments away from zero".7 - Java
Math.roundreturns "the closest long to the argument, with ties rounding to positive infinity".8RoundingModehasUP,DOWN,CEILING,FLOOR,HALF_UP,HALF_DOWN,HALF_EVENandUNNECESSARY, for use withBigDecimal.9 Java'sHALF_UPmeans ties away from zero: the RoundingMode table rounds -2.5 to -3 underHALF_UP.9 - C#
Math.Round"uses the round to nearest even convention" by default.10MidpointRoundingaddsAwayFromZero,ToZero,ToNegativeInfinityandToPositiveInfinity.11 - Go
math.Round"returns the nearest integer, rounding half away from zero", andmath.RoundToEvenrounds "ties to even".12 - Rust
roundrounds "half-way between two integers" "away from 0.0", andround_ties_evenrounds them "to the number with an even least significant digit".13 - C has
fesetroundto change the IEEE rounding mode of arithmetic.6 GCC assumes round-to-nearest unless the program is built with-frounding-math, which "should be specified for programs that change the FP rounding mode dynamically".14 - SQL in PostgreSQL: for
numeric, "ties are broken by rounding away from zero". Fordouble precision, "the tie-breaking behavior is platform dependent".15 - CSS has
round()with the strategiesnearest,up,downandto-zero. Withnearest, a value halfway between two targets "will be rounded up", as in JavaScriptMath.round().16
from decimal import (
ROUND_05UP,
ROUND_CEILING,
ROUND_DOWN,
ROUND_FLOOR,
ROUND_HALF_DOWN,
ROUND_HALF_EVEN,
ROUND_HALF_UP,
ROUND_UP,
Decimal,
localcontext,
)
modes = [ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_05UP]
for mode in modes:
row = [str(Decimal(s).quantize(Decimal(1), rounding=mode)) for s in ["2.5", "-2.5", "2.6", "-2.4"]]
print(f"{mode:16} {' '.join(f'{v:>3}' for v in row)}")
def drift(mode, steps):
with localcontext() as ctx:
ctx.prec = 3
ctx.rounding = mode
x = Decimal("1.00")
y = Decimal("-0.555")
for _ in range(steps):
x = (x - y) + y
return x
print("Goldberg, 10 steps, half up: ", drift(ROUND_HALF_UP, 10))
print("Goldberg, 10 steps, half even:", drift(ROUND_HALF_EVEN, 10))
print("round(2.675, 2):", round(2.675, 2))
print("Decimal('2.675'), half up:", Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
ROUND_HALF_EVEN 2 -2 3 -2
ROUND_HALF_UP 3 -3 3 -2
ROUND_HALF_DOWN 2 -2 3 -2
ROUND_UP 3 -3 3 -3
ROUND_DOWN 2 -2 2 -2
ROUND_CEILING 3 -2 3 -2
ROUND_FLOOR 2 -3 2 -3
ROUND_05UP 2 -2 2 -2
Goldberg, 10 steps, half up: 1.10
Goldberg, 10 steps, half even: 1.00
round(2.675, 2): 2.67
Decimal('2.675'), half up: 2.68
- Verdict: native. The built-in
rounduses half to even, and thedecimalmodule has eight rounding modes. - In
decimal,ROUND_HALF_UPmeans ties away from zero, so -2.5 becomes -3.ROUND_UPmeans away from zero for every value, not only ties. - The drift test repeats Goldberg's example with three digits. Under half up the value climbs by 0.01 per step. Under half to even it stays at 1.00.
round(2.675, 2)gives 2.67 because the float is a little below 2.675. ADecimalbuilt from the string rounds to 2.68.
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
int main() {
std::cout << " x round rint floor ceil trunc\n";
for (double x : {0.5, 1.5, 2.5, -0.5, -1.5, -2.5}) {
std::cout << std::setw(5) << x;
for (double r : {std::round(x), std::rint(x), std::floor(x), std::ceil(x), std::trunc(x)}) {
std::cout << std::setw(6) << r + 0.0;
}
std::cout << "\n";
}
std::ostringstream out;
out << std::fixed << std::setprecision(0) << 0.5 << " " << 1.5 << " " << 2.5;
out << std::setprecision(2) << " " << 0.125 << " " << 0.375 << " " << 2.675;
std::cout << "printed: " << out.str() << "\n";
std::cout << "lround(-2.5): " << std::lround(-2.5) << "\n";
}
x round rint floor ceil trunc
0.5 1 0 0 1 0
1.5 2 2 1 2 1
2.5 3 2 2 3 2
-0.5 -1 0 -1 0 0
-1.5 -2 -2 -2 -1 -1
-2.5 -3 -2 -3 -2 -2
printed: 0 2 2 0.12 0.38 2.67
lround(-2.5): -3
- Verdict: native.
std::roundrounds half away from zero, andstd::rintuses the current IEEE mode, which is to nearest, ties to even, by default. - The table adds
0.0to each result so that negative zero prints as 0. - Printing with
std::fixedalso rounds. In this run the ties 0.5, 2.5, 0.125 and 0.375 go to the even digit, and 2.675 prints as 2.67 because the double is below 2.675.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
String[] inputs = {"2.5", "-2.5", "2.6", "-2.4"};
for (RoundingMode mode : RoundingMode.values()) {
StringBuilder row = new StringBuilder(String.format("%-12s", mode));
for (String s : inputs) {
try {
row.append(String.format("%4s", new BigDecimal(s).setScale(0, mode)));
} catch (ArithmeticException e) {
row.append(" !");
}
}
System.out.println(row);
}
System.out.println("Math.round(2.5): " + Math.round(2.5) + ", Math.round(-2.5): " + Math.round(-2.5));
System.out.println("Math.rint(2.5): " + Math.rint(2.5) + ", Math.rint(3.5): " + Math.rint(3.5));
System.out.println("(int) -2.7: " + (int) -2.7);
System.out.println("new BigDecimal(\"2.675\") HALF_UP: " + new BigDecimal("2.675").setScale(2, RoundingMode.HALF_UP));
System.out.println("new BigDecimal(2.675) HALF_UP: " + new BigDecimal(2.675).setScale(2, RoundingMode.HALF_UP));
}
}
UP 3 -3 3 -3
DOWN 2 -2 2 -2
CEILING 3 -2 3 -2
FLOOR 2 -3 2 -3
HALF_UP 3 -3 3 -2
HALF_DOWN 2 -2 3 -2
HALF_EVEN 2 -2 3 -2
UNNECESSARY ! ! ! !
Math.round(2.5): 3, Math.round(-2.5): -2
Math.rint(2.5): 2.0, Math.rint(3.5): 4.0
(int) -2.7: -2
new BigDecimal("2.675") HALF_UP: 2.68
new BigDecimal(2.675) HALF_UP: 2.67
- Verdict: native.
java.math.RoundingModehas eight modes forBigDecimal. UNNECESSARYthrowsArithmeticExceptionwhen the result is not exact, here shown as!.Math.roundsends ties toward plus infinity, andMath.rintsends them to the even neighbour. A cast tointtruncates toward zero.new BigDecimal(2.675)holds the exact value of the double, which is a little below 2.675, so it rounds down.
#include <fenv.h>
#include <math.h>
#include <stdio.h>
int main(void) {
const int modes[] = {FE_TONEAREST, FE_UPWARD, FE_DOWNWARD, FE_TOWARDZERO};
const char *names[] = {"FE_TONEAREST", "FE_UPWARD", "FE_DOWNWARD", "FE_TOWARDZERO"};
volatile double one = 1.0;
volatile double three = 3.0;
volatile double tie = 2.5;
double third[4];
double pos[4];
double neg[4];
for (int i = 0; i < 4; i++) {
fesetround(modes[i]);
third[i] = one / three;
pos[i] = nearbyint(tie);
neg[i] = nearbyint(-tie);
}
fesetround(FE_TONEAREST);
for (int i = 0; i < 4; i++) {
printf("%-13s 1/3 = %.20f nearbyint(2.5) = %2.0f nearbyint(-2.5) = %2.0f\n", names[i], third[i], pos[i], neg[i]);
}
printf("round(2.5) = %.0f, round(-2.5) = %.0f\n", round(tie), round(-tie));
printf("(int)-2.7 = %d\n", (int)-2.7);
return 0;
}
FE_TONEAREST 1/3 = 0.33333333333333331483 nearbyint(2.5) = 2 nearbyint(-2.5) = -2
FE_UPWARD 1/3 = 0.33333333333333337034 nearbyint(2.5) = 3 nearbyint(-2.5) = -2
FE_DOWNWARD 1/3 = 0.33333333333333331483 nearbyint(2.5) = 2 nearbyint(-2.5) = -3
FE_TOWARDZERO 1/3 = 0.33333333333333331483 nearbyint(2.5) = 2 nearbyint(-2.5) = -2
round(2.5) = 3, round(-2.5) = -3
(int)-2.7 = -2
- Verdict: native.
fesetroundchanges the IEEE rounding mode of arithmetic, andnearbyintandrintround to an integer with the current mode. - The quotient
1/3changes with the mode: upward gives the double above one third, and the other modes give the double below it. roundignores the mode and always rounds half away from zero. A cast tointtruncates toward zero.- The operands are
volatile, so the compiler cannot fold the division at compile time with the default mode. The program sets the mode back to nearest before it callsprintf, because the C library can use the current mode when it prints.
using System;
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
MidpointRounding[] modes =
{
MidpointRounding.ToEven,
MidpointRounding.AwayFromZero,
MidpointRounding.ToZero,
MidpointRounding.ToNegativeInfinity,
MidpointRounding.ToPositiveInfinity,
};
foreach (var mode in modes)
{
Console.WriteLine($"{mode,-19}{Math.Round(2.5, mode),4}{Math.Round(-2.5, mode),4}{Math.Round(2.6, mode),4}{Math.Round(-2.4, mode),4}");
}
Console.WriteLine($"Math.Round(2.5): {Math.Round(2.5)}, Math.Round(3.5): {Math.Round(3.5)}");
Console.WriteLine($"Math.Round(2.675, 2): {Math.Round(2.675, 2)}");
Console.WriteLine($"2.675 * 100 == 267.5: {2.675 * 100 == 267.5}");
Console.WriteLine($"Math.Round(2.675m, 2): {Math.Round(2.675m, 2)}");
Console.WriteLine($"Math.Round(2.665m, 2): {Math.Round(2.665m, 2)}");
Console.WriteLine($"(int)-2.7: {(int)-2.7}");
ToEven 2 -2 3 -2
AwayFromZero 3 -3 3 -2
ToZero 2 -2 2 -2
ToNegativeInfinity 2 -3 2 -3
ToPositiveInfinity 3 -2 3 -2
Math.Round(2.5): 2, Math.Round(3.5): 4
Math.Round(2.675, 2): 2.68
2.675 * 100 == 267.5: True
Math.Round(2.675m, 2): 2.68
Math.Round(2.665m, 2): 2.66
(int)-2.7: -2
- Verdict: native.
Math.Rounduses half to even by default, andMidpointRoundingselects the other rules. ToZero,ToNegativeInfinityandToPositiveInfinityare directed: they apply to every value, not only to ties.- The
decimalvalue2.675mis exact, so it is a true tie and goes to the even digit 8. Thedouble2.675 is a little less than 2.675, so the correctly rounded result is 2.67, which Python'sroundgives.Math.Roundgives 2.68 here. The product 2.675 * 100 rounds to exactly 267.5 in binary64, so a method that scales the value first sees a tie. Do not depend on the last digit ofMath.Roundon adouble. Usedecimalwhen the decimal digits matter.
const halfAway = (x) => Math.sign(x) * Math.round(Math.abs(x));
const halfEven = (x) => {
const r = Math.round(x);
return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r;
};
const pad = (v) => String(v + 0).padStart(5);
console.log(" x round away even floor ceil trunc");
for (const x of [0.5, 1.5, 2.5, -0.5, -1.5, -2.5]) {
const cells = [Math.round(x), halfAway(x), halfEven(x), Math.floor(x), Math.ceil(x), Math.trunc(x)];
console.log(pad(x) + " " + cells.map(pad).join(" "));
}
console.log("Object.is(Math.round(-0.5), -0):", Object.is(Math.round(-0.5), -0));
console.log("(2.5).toFixed(0):", (2.5).toFixed(0), "(-2.5).toFixed(0):", (-2.5).toFixed(0));
x round away even floor ceil trunc
0.5 1 1 0 0 1 0
1.5 2 2 2 1 2 1
2.5 3 3 2 2 3 2
-0.5 0 -1 0 -1 0 0
-1.5 -1 -2 -2 -2 -1 -1
-2.5 -2 -3 -2 -3 -2 -2
Object.is(Math.round(-0.5), -0): true
(2.5).toFixed(0): 3 (-2.5).toFixed(0): -3
- Verdict: native.
Math.round,Math.floor,Math.ceilandMath.truncare built in. JavaScript has no built-in half to even or half away from zero, so the code writes them. Math.roundsends a tie toward plus infinity: 2.5 becomes 3 but -2.5 becomes -2.Math.round(-0.5)is negative zero, and the table adds 0 to print it as 0.toFixeduses another rule thanMath.round: in this run it rounds -2.5 to -3.
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(" x Round Even Floor Ceil Trunc")
for _, x := range []float64{0.5, 1.5, 2.5, -0.5, -1.5, -2.5} {
fmt.Printf("%5.1f", x)
for _, r := range []float64{math.Round(x), math.RoundToEven(x), math.Floor(x), math.Ceil(x), math.Trunc(x)} {
fmt.Printf("%6.0f", r+0)
}
fmt.Println()
}
fmt.Printf("Sprintf %%.0f: %.0f %.0f %.0f\n", 0.5, 1.5, 2.5)
fmt.Printf("Sprintf %%.2f of 2.675: %.2f\n", 2.675)
x := -2.7
fmt.Println("int(-2.7):", int(x))
fmt.Println("-7 / 2:", -7/2)
}
x Round Even Floor Ceil Trunc
0.5 1 0 0 1 0
1.5 2 2 1 2 1
2.5 3 2 2 3 2
-0.5 -1 0 -1 0 0
-1.5 -2 -2 -2 -1 -1
-2.5 -3 -2 -3 -2 -2
Sprintf %.0f: 0 2 2
Sprintf %.2f of 2.675: 2.67
int(-2.7): -2
-7 / 2: -3
- Verdict: native.
math.Roundrounds half away from zero, andmath.RoundToEvenrounds ties to even. - Several results are negative zero. The table adds 0 to each result, so they print as 0.
fmtrounds ties to even when it prints, so%.0fgives 0, 2 and 2.- A conversion to
intand integer division both truncate toward zero.
fn main() {
println!(" x round even floor ceil trunc");
for x in [0.5_f64, 1.5, 2.5, -0.5, -1.5, -2.5] {
let row = [x.round(), x.round_ties_even(), x.floor(), x.ceil(), x.trunc()];
let cells: Vec<String> = row.iter().map(|r| format!("{:6}", r + 0.0)).collect();
println!("{x:5}{}", cells.join(""));
}
println!("format {{:.0}}: {:.0} {:.0} {:.0}", 0.5, 1.5, 2.5);
println!("format {{:.2}} of 2.675: {:.2}", 2.675);
println!("-2.7 as i32: {}", -2.7_f64 as i32);
println!("-7 / 2: {}, (-7_i32).div_euclid(2): {}", -7 / 2, (-7_i32).div_euclid(2));
}
x round even floor ceil trunc
0.5 1 0 0 1 0
1.5 2 2 1 2 1
2.5 3 2 2 3 2
-0.5 -1 0 -1 0 0
-1.5 -2 -2 -2 -1 -1
-2.5 -3 -2 -3 -2 -2
format {:.0}: 0 2 2
format {:.2} of 2.675: 2.67
-2.7 as i32: -2
-7 / 2: -3, (-7_i32).div_euclid(2): -4
- Verdict: native.
roundrounds half away from zero, andround_ties_evenrounds ties to even. ascasts from float to integer truncate toward zero. Integer/also truncates, anddiv_euclidrounds toward minus infinity for a positive divisor.- The
{:.0}format rounds ties to even, so it does not agree withround.
Variations and related ideas
- Stochastic rounding. The value is rounded up or down at random, with a probability that depends on its distance from each neighbour.1
- Round to odd. A first rounding to an odd last digit avoids the error of rounding twice.1
- Integer division. Integer division is rounding too: truncated division rounds toward zero and floored division rounds toward minus infinity (Integer division and modulo).
- Decimal types. Rounding a binary float to two decimals cannot be exact, because the float is not exact. A decimal type such as Python's
Decimalor Java'sBigDecimalrounds the decimal digits exactly (Floating-point rounding error, Fixed-point arithmetic).
Pitfalls
Assuming that round means half up
round(2.5) is 2 in Python and C#, 3 in Go, Rust and JavaScript. round(-2.5) is -2 in Python, C#, JavaScript and Java, and -3 in Go and Rust.210121378 Code ported from one language to another can change its results at every tie.
Rounding a binary float to decimal places
Python's docs: "round(2.675, 2) gives 2.67 instead of the expected 2.68". This is because 2.675 as a float is a little less than 2.675.2 The rounding mode is not the cause, and no mode fixes it. Use a decimal type for values that must round exactly in decimal (Floating-point rounding error).
Rounding twice
"Rounding a number twice in succession to different levels of precision, with the latter precision being coarser, is not guaranteed to give the same result as rounding once to the final precision".1 For example, 9.46 rounds to 9.5 at one decimal and then to 10, but 9.46 rounded once to an integer is 9.1
Truncation that adds up
The Vancouver Stock Exchange started a new index at 1000.000 in 1982. After 22 months it "had fallen to about 520, although the market appeared to be rising".1 The index was recalculated thousands of times a day and "always being truncated (rounded down) to 3 decimal places".1 With rounding to nearest, the value was 1098.892, not 524.811.1
Changing the mode in C without telling the compiler
Access to the floating-point environment "is only meaningful when #pragma STDC FENV_ACCESS is set to ON".6 Without it, the compiler may fold constants with the default mode. GCC needs -frounding-math, which "disables constant folding of floating-point expressions at compile time".14
Cost
The rounding of float arithmetic is done by the hardware in every operation, with no extra cost. Library rounding to an integer is a single function call. Rounding a Decimal or a BigDecimal costs more, because it works on the decimal digits (Arbitrary-precision arithmetic). The real cost is in the results: a biased rule can move a long sum far from the true value, as the Vancouver index shows.1
History
Half to even is old. In 1906 Robert Simpson Woodward called it "the computer's rule". This shows that the human computers who made mathematical tables used it then.1 The name bankers' rounding is less clear: "If this rounding method was ever a standard in banking, the evidence has proved extremely difficult to find."1 Reiser and Knuth gave a reason to prefer round to even in 1975.4 IEEE 754 made round to nearest, ties to even, the default for binary floating point.5
References
- Rounding, Wikipedia, the lead, Directed rounding to an integer, Rounding to the nearest integer, Double rounding, and History
- Built-in Functions, Python Software Foundation, round()
- decimal, Decimal fixed point and floating point arithmetic, Python Software Foundation, Quick-start tutorial, and Rounding modes
- David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic, ACM Computing Surveys 23(1), March 1991 (edited reprint by Sun Microsystems), Theorem 5 and its example, and the section Rounding Modes
- IEEE 754, Wikipedia, Rounding rules
- Floating-point environment (C), cppreference.com, the description, fesetround, and the FE_ rounding macros
- Math.round(), MDN Web Docs, Description
- Math (Java SE 27 and JDK 27), Oracle, Math.round(double), and Math.rint
- RoundingMode (Java SE 27 and JDK 27), Oracle, the enum description and the constants
- Math.Round Method, Microsoft Learn, Remarks, Midpoint values and rounding conventions
- MidpointRounding Enum, Microsoft Learn, Fields
- math package, The Go Authors, func Round, and func RoundToEven
- Primitive Type f64, The Rust Project, the methods round and round_ties_even
- GCC Manual, Options That Control Optimization, Free Software Foundation, -frounding-math
- PostgreSQL Documentation, 9.3. Mathematical Functions and Operators, The PostgreSQL Global Development Group, round
- round(), MDN Web Docs, Parameters
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag G7MRNR Edit this page History Report an error Markdown