Programming Search⌘K

Taskintro

Round a number

Also called round a float, round half away from zero, round half to even, banker's rounding, round to n decimal places, floor and ceiling, truncate a number.

Round a float to an integer or to n decimal places. Each library has its own rule for a half, and a decimal such as 2.675 is not exact in binary.

Task

Round a float to the nearest integer. When the float is exactly halfway between two integers, choose the integer that is farther from zero.

The function round_half_away(x) returns an integer. For example, round_half_away(2.4) is 2, round_half_away(2.5) is 3, and round_half_away(-2.5) is -3.

Each rounding function answers two questions. The first is the direction: to the nearest integer, down, up, or toward zero. The second is the rule for a half, when the two nearest integers are equally close:

Rule 2.5 -2.5 3.5 Functions
floor, toward minus infinity 2 -3 3 math.floor, Math.floor, floor
ceiling, toward plus infinity 3 -2 4 math.ceil, Math.ceil, ceil
truncation, toward zero 2 -2 3 math.trunc, Math.trunc, trunc
nearest, half away from zero 3 -3 4 C round, Go math.Round, Rust f64::round
nearest, half to even 2 -2 4 Python round, C# Math.Round, Go math.RoundToEven
nearest, half toward plus infinity 3 -2 4 JavaScript Math.round, Java Math.round

The rule for a half is the one that differs most between libraries. The same call round(2.5) gives 2 in Python and 3 in C. The .NET documentation gives another name for a half to even: "Rounding to nearest even, or banker's rounding"1.

Rounding to n decimal places has one more problem. Most decimal fractions are not exact in binary, so the float nearest to 2.675 is a little below 2.675, and round(2.675, 2) in Python gives 2.67. See Floating-point arithmetic and decimal-arithmetic.

Solutions

Language Half away from zero Half to even To n decimal places
Python the floor of the magnitude, then a test round(x) round(x, n)
JavaScript, TypeScript Math.sign(x) * Math.round(Math.abs(x)) no built-in function x.toFixed(n) gives a string
Java Math.round on the magnitude Math.rint(x) BigDecimal.setScale(n, RoundingMode.HALF_UP)
C, C++ llround(x) rint(x) in the default rounding mode printf("%.2f", x)
C# Math.Round(x, MidpointRounding.AwayFromZero) Math.Round(x) Math.Round(x, n, mode)
Go math.Round(x) math.RoundToEven(x) strconv.FormatFloat(x, 'f', n, 64)
Rust x.round() x.round_ties_even() format!("{:.2}", x)
Bash the first digit after the point printf '%.0f' printf '%.2f'
  • Python. round(x) rounds to the nearest integer, and "if two multiples are equally close, rounding is done toward the even choice"2. So round(0.5) is 0 and round(2.5) is 2. math.floor(x) is "the largest integer less than or equal to x"3, math.ceil(x) is "the smallest integer greater than or equal to x"3, and math.trunc(x) "rounds toward 0"3. The solution rounds the magnitude: it takes the floor, then adds 1 when the fraction is 0.5 or more.
  • JavaScript. When "the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞"4, so Math.round(-2.5) is -2. The solution rounds the magnitude and sets the sign after. Math.trunc "returns the integer part of a number by removing any fractional digits"5. toFixed "returns a string representing this number using fixed-point notation with the specified number of decimal places"6.
  • TypeScript. The same code as JavaScript.
  • Java. Math.round "Returns the closest long to the argument, with ties rounding to positive infinity"7. Math.rint gives a double, and "If two double values that are mathematical integers are equally close, the result is the integer value that is even"7. For decimal places, RoundingMode "Specifies a rounding policy for numerical operations capable of discarding precision"8: HALF_UP and HALF_EVEN are two of its constants.
  • C. round and llround round to the nearest integer, "rounding halfway cases away from zero, regardless of the current rounding mode"9. In the default rounding mode, rint is different: "halfway cases are rounded to even rather than away from zero"10. For printf with %f, "The precision specifies the number of decimal places"11.
  • C++. std::round and std::llround in <cmath> have the same rule, "rounding halfway cases away from zero, regardless of the current rounding mode"12.
  • C#. Math.Round(Double) "Rounds a double-precision floating-point value to the nearest integral value, and rounds midpoint values to the nearest even number"1. For a half away from zero, give the mode MidpointRounding.AwayFromZero. The overload with an Int32 "Rounds a double-precision floating-point value to a specified number of fractional digits using the specified rounding convention"1.
  • Go. "Round returns the nearest integer, rounding half away from zero"13, and "RoundToEven returns the nearest integer, rounding ties to even"13. For decimal places, the precision of strconv.FormatFloat with the format 'f' "is the number of digits after the decimal point"14.
  • Rust. f64::round returns the nearest integer: "If a value is half-way between two integers, round away from 0.0"15. f64::round_ties_even "Rounds half-way cases to the number with an even least significant digit"15. In a format string, the precision of a float "indicates how many digits after the decimal point should be printed"16.
  • Bash. Bash arithmetic has integers only, so the solution reads the decimal text: the integer part, and the first digit after the point. The printf builtin knows "the standard printf(3) format characters"17, so printf '%.2f' rounds a number to two decimal places.

The rules of Python, with round and the functions of math:

import math

for x in [2.5, -2.5, 3.5, 0.5]:
    print(x, round(x), math.floor(x), math.ceil(x), math.trunc(x))
print(round(2.675, 2), round(3.14159, 2))
Output
2.5 2 2 3 2
-2.5 -2 -3 -2 -2
3.5 4 3 4 3
0.5 0 0 1 0
2.67 3.14

JavaScript rounds a half toward plus infinity, and -0.5 rounds to negative zero:

for (const x of [2.5, -2.5, 3.5, -0.5]) {
  console.log(x, Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x));
}
console.log((2.55).toFixed(1), (2.35).toFixed(1), (1.005).toFixed(2));
Output
2.5 3 2 3 2
-2.5 -2 -3 -2 -2
3.5 4 3 4 3
-0.5 -0 -1 -0 -0
2.5 2.4 1.00

C has both rules, and printf rounds the binary value of the float:

#include <math.h>
#include <stdio.h>

int main(void) {
    double xs[] = {2.5, -2.5, 3.5};
    for (int i = 0; i < 3; i++) {
        double x = xs[i];
        printf("%4.1f: round %2.0f, rint %2.0f, floor %2.0f, ceil %2.0f, trunc %2.0f\n",
               x, round(x), rint(x), floor(x), ceil(x), trunc(x));
    }
    printf("%.2f %.2f\n", 2.675, 1.005);
}
Output
 2.5: round  3, rint  2, floor  2, ceil  3, trunc  2
-2.5: round -3, rint -2, floor -3, ceil -2, trunc -2
 3.5: round  4, rint  4, floor  3, ceil  4, trunc  3
2.67 1.00

In C#, Math.Round without a mode rounds a half to even:

using System;
using System.Globalization;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine($"{Math.Round(2.5)} {Math.Round(3.5)} {Math.Round(-2.5)}");
Console.WriteLine($"{Math.Round(2.5, MidpointRounding.AwayFromZero)} {Math.Round(-2.5, MidpointRounding.AwayFromZero)}");
Console.WriteLine($"{Math.Round(2.675, 2)} {Math.Round(2.675m, 2, MidpointRounding.AwayFromZero)}");
Output
2 4 -2
3 -3
2.68 2.68

The last line rounds 2.675 to two decimal places. For the double value, Math.Round gives 2.68 on this run, but Python and C give 2.67 for the same float, as the blocks above show. A decimal value, such as 2.675m, holds 2.675 exactly, so the result follows only the mode.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • half-even-up, half-zero, half-negative, half-negative-small: halves where the rule matters. Half to even gives 2, 0, -2 and 0; half away from zero gives 3, 1, -3 and -1.
  • half-odd-up: 1.5 rounds to 2 with both rules.
  • negative-below-half: -0.4 rounds to 0, not to negative zero. A float function such as Math.round can give -0.
  • near-half: 0.49999999999999994 is the largest float below 0.5. It rounds to 0.
  • large-odd: 4503599627370497 is 2 to the power 52, plus 1. It is already an integer.
  • large-half-negative: -1000000000000000.5 is exact in a float, and it rounds to -1000000000000001.
  • zero: 0.0 rounds to 0.

Pitfalls

  • floor(x + 0.5) is not a correct rounding. The sum x + 0.5 is a float, and it can round up. For 0.49999999999999994, the sum rounds to 1.0. For 4503599627370497, the sum is halfway between two floats and rounds to 4503599627370498. Both results are wrong:

This code runs but gives a wrong answer on purpose.

import math

for x in [0.49999999999999994, 4503599627370497.0]:
    print(x, math.floor(x + 0.5), round(x))
Output
0.49999999999999994 1 0
4503599627370497.0 4503599627370498 4503599627370497
  • The decimal text is not the value. The Python manual says that round(2.675, 2) "gives 2.67 instead of the expected 2.68"2, and "This is not a bug"2. The float nearest to 2.675 is a little smaller than 2.675. MDN gives the same example for toFixed: (2.55).toFixed(1) is '2.5'6. For exact decimal rounding, use a decimal type, such as decimal in C#, BigDecimal in Java, or the decimal module in Python.

  • A rounded float is still a float. Math.round in JavaScript, round in C and math.Round in Go return a float. Convert the result to an integer type only when it fits; a float can be much larger than the largest 64-bit integer. See convert-between-numeric-types.

  • Negative zero. In JavaScript, Math.round(-0.4) is -0, and a float function in other languages can also give -0. It is equal to 0, but it prints as -0 in some languages. See IEEE 754.

  • Rounding money. A rule for money can ask for a specific rule for a half. Do not depend on the default of the library; give the mode in the call. See represent-money.

  • Do integer arithmetic: integer division, which rounds toward zero in most languages.
  • Compare floating-point numbers: compare floats with a tolerance.
  • format-a-number: print a number with a fixed number of decimal places.
  • convert-between-numeric-types: convert a float to an integer type.

See also the concepts Rounding modes, Floating-point arithmetic, IEEE 754 and decimal-arithmetic.

Code

The build runs the native tests of each language in a pinned toolchain.

round_half_away.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/round-a-number/.
import math


def round_half_away(x: float) -> int:
    """Rounds x to the nearest integer; a half goes away from zero."""
    # The built-in round() rounds a half to the even integer. Round the
    # magnitude, then set the sign. m - f is exact, so the test does not
    # round. floor(x + 0.5) is wrong for 0.49999999999999994.
    m = abs(x)
    f = math.floor(m)
    if m - f >= 0.5:
        f += 1
    return -f if x < 0 else f
test_round_half_away.py 42 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/round-a-number/.
import math

import pytest

from round_half_away import round_half_away

CASES = {
    "down": (2.4, 2),
    "up": (2.6, 3),
    "negative": (-2.6, -3),
    "integer": (7.0, 7),
    "half-even-up": (2.5, 3),
    "half-odd-up": (1.5, 2),
    "half-zero": (0.5, 1),
    "half-negative": (-2.5, -3),
    "half-negative-small": (-0.5, -1),
    "negative-below-half": (-0.4, 0),
    "near-half": (0.49999999999999994, 0),
    "zero": (0.0, 0),
    "large-odd": (4503599627370497.0, 4503599627370497),
    "large-half-negative": (-1000000000000000.5, -1000000000000001),
}


@pytest.mark.parametrize("case", CASES)
def test_round_half_away(case):
    x, want = CASES[case]
    got = round_half_away(x)
    assert type(got) is int
    assert got == want


def test_builtin_round_is_half_even():
    assert (round(0.5), round(1.5), round(2.5), round(-0.5)) == (0, 2, 2, 0)
    assert round(2.675, 2) == 2.67


def test_floor_plus_half_is_wrong():
    assert math.floor(0.49999999999999994 + 0.5) == 1
    assert math.floor(4503599627370497.0 + 0.5) == 4503599627370498
round_half_away.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

#pragma once

#include <cmath>

// Rounds x to the nearest integer; a half goes away from zero.
inline long long round_half_away(double x) {
    // std::llround rounds a half away from zero in each rounding mode.
    return std::llround(x);
}
test_round_half_away.cpp 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

#include "round_half_away.hpp"

#include <cmath>
#include <cstdio>

namespace {

int failures = 0;

void check(const char *label, double x, long long want) {
    long long got = round_half_away(x);
    if (got != want) {
        std::fprintf(stderr, "case %s: got %lld, want %lld\n", label, got, want);
        ++failures;
    }
}

}  // namespace

int main() {
    check("down", 2.4, 2);
    check("up", 2.6, 3);
    check("negative", -2.6, -3);
    check("integer", 7.0, 7);
    check("half-even-up", 2.5, 3);
    check("half-odd-up", 1.5, 2);
    check("half-zero", 0.5, 1);
    check("half-negative", -2.5, -3);
    check("half-negative-small", -0.5, -1);
    check("negative-below-half", -0.4, 0);
    check("near-half", 0.49999999999999994, 0);
    check("zero", 0.0, 0);
    check("large-odd", 4503599627370497.0, 4503599627370497LL);
    check("large-half-negative", -1000000000000000.5, -1000000000000001LL);
    if (std::nearbyint(2.5) != 2.0 || std::floor(-2.5) != -3.0 || std::trunc(-2.5) != -2.0) {
        std::fprintf(stderr, "library modes\n");
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::puts("ok");
    return 0;
}
RoundHalfAway.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

final class RoundHalfAway {
  private RoundHalfAway() {}

  /**
   * Rounds x to the nearest integer; a half goes away from zero. Math.round rounds a half toward
   * positive infinity, so Math.round(-2.5) is -2. Round the magnitude, then set the sign.
   */
  static long roundHalfAway(double x) {
    long r = Math.round(Math.abs(x));
    return x < 0 ? -r : r;
  }
}
RoundHalfAwayTest.java 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class RoundHalfAwayTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("down", 2.4, 2L),
        Arguments.of("up", 2.6, 3L),
        Arguments.of("negative", -2.6, -3L),
        Arguments.of("integer", 7.0, 7L),
        Arguments.of("half-even-up", 2.5, 3L),
        Arguments.of("half-odd-up", 1.5, 2L),
        Arguments.of("half-zero", 0.5, 1L),
        Arguments.of("half-negative", -2.5, -3L),
        Arguments.of("half-negative-small", -0.5, -1L),
        Arguments.of("negative-below-half", -0.4, 0L),
        Arguments.of("near-half", 0.49999999999999994, 0L),
        Arguments.of("zero", 0.0, 0L),
        Arguments.of("large-odd", 4503599627370497.0, 4503599627370497L),
        Arguments.of("large-half-negative", -1000000000000000.5, -1000000000000001L));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void check(String name, double x, long want) {
    assertEquals(want, RoundHalfAway.roundHalfAway(x), name);
  }

  @Test
  void libraryModes() {
    assertEquals(-2L, Math.round(-2.5));
    assertEquals(2.0, Math.rint(2.5));
    assertEquals(
        "2.68", new BigDecimal("2.675").setScale(2, RoundingMode.HALF_UP).toPlainString());
    assertEquals(
        "2.68", new BigDecimal("2.675").setScale(2, RoundingMode.HALF_EVEN).toPlainString());
    assertEquals("2.67", new BigDecimal(2.675).setScale(2, RoundingMode.HALF_UP).toPlainString());
  }
}
round_half_away.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

#include "round_half_away.h"

#include <math.h>

long long round_half_away(double x) {
    // llround rounds a half away from zero in each rounding mode.
    return llround(x);
}
round_half_away.h 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

#ifndef ROUND_HALF_AWAY_H
#define ROUND_HALF_AWAY_H

// Rounds x to the nearest integer; a half goes away from zero.
long long round_half_away(double x);

#endif
test_round_half_away.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

#include "round_half_away.h"

#include <math.h>
#include <stdio.h>

static int failures = 0;

static void check(const char *label, double x, long long want) {
    long long got = round_half_away(x);
    if (got != want) {
        fprintf(stderr, "case %s: got %lld, want %lld\n", label, got, want);
        failures++;
    }
}

int main(void) {
    check("down", 2.4, 2);
    check("up", 2.6, 3);
    check("negative", -2.6, -3);
    check("integer", 7.0, 7);
    check("half-even-up", 2.5, 3);
    check("half-odd-up", 1.5, 2);
    check("half-zero", 0.5, 1);
    check("half-negative", -2.5, -3);
    check("half-negative-small", -0.5, -1);
    check("negative-below-half", -0.4, 0);
    check("near-half", 0.49999999999999994, 0);
    check("zero", 0.0, 0);
    check("large-odd", 4503599627370497.0, 4503599627370497LL);
    check("large-half-negative", -1000000000000000.5, -1000000000000001LL);
    // rint uses the current rounding mode; the default mode rounds a half to even.
    if (rint(2.5) != 2.0 || floor(-2.5) != -3.0 || ceil(-2.5) != -2.0 || trunc(-2.5) != -2.0) {
        fprintf(stderr, "library modes\n");
        failures++;
    }
    if (failures != 0) {
        return 1;
    }
    puts("ok");
    return 0;
}
Rounding.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.
using System;

public static class Rounding
{
    // Rounds x to the nearest integer; a half goes away from zero.
    // Math.Round(x) without a mode rounds a half to the even integer.
    public static long RoundHalfAway(double x)
    {
        return (long)Math.Round(x, MidpointRounding.AwayFromZero);
    }
}
RoundingTests.cs 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.
using System;
using Xunit;

public sealed class RoundingTests
{
    public static TheoryData<string, double, long> Cases => new()
    {
        { "down", 2.4, 2 },
        { "up", 2.6, 3 },
        { "negative", -2.6, -3 },
        { "integer", 7.0, 7 },
        { "half-even-up", 2.5, 3 },
        { "half-odd-up", 1.5, 2 },
        { "half-zero", 0.5, 1 },
        { "half-negative", -2.5, -3 },
        { "half-negative-small", -0.5, -1 },
        { "negative-below-half", -0.4, 0 },
        { "near-half", 0.49999999999999994, 0 },
        { "zero", 0.0, 0 },
        { "large-odd", 4503599627370497.0, 4503599627370497 },
        { "large-half-negative", -1000000000000000.5, -1000000000000001 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, double x, long want)
    {
        Assert.True(want == Rounding.RoundHalfAway(x), name);
    }

    [Fact]
    public void DefaultIsToEven()
    {
        Assert.Equal(2.0, Math.Round(2.5));
        Assert.Equal(-2.0, Math.Round(-2.5));
        Assert.Equal(3.0, Math.Round(2.5, MidpointRounding.AwayFromZero));
    }
}
round_half_away.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

/**
 * Rounds x to the nearest integer; a half goes away from zero.
 * Math.round rounds a half toward +Infinity, so Math.round(-2.5) is -2.
 * Round the magnitude, then set the sign. Adding 0 turns -0 into 0.
 * @param {number} x
 * @returns {number}
 */
export function roundHalfAway(x) {
  return Math.sign(x) * Math.round(Math.abs(x)) + 0;
}
round_half_away.test.js 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.
import assert from "node:assert/strict";
import { test } from "node:test";

import { roundHalfAway } from "./round_half_away.js";

const cases = [
  ["down", 2.4, 2],
  ["up", 2.6, 3],
  ["negative", -2.6, -3],
  ["integer", 7.0, 7],
  ["half-even-up", 2.5, 3],
  ["half-odd-up", 1.5, 2],
  ["half-zero", 0.5, 1],
  ["half-negative", -2.5, -3],
  ["half-negative-small", -0.5, -1],
  ["negative-below-half", -0.4, 0],
  ["near-half", 0.49999999999999994, 0],
  ["zero", 0.0, 0],
  ["large-odd", 4503599627370497.0, 4503599627370497],
  ["large-half-negative", -1000000000000000.5, -1000000000000001],
];

for (const [name, x, want] of cases) {
  test(name, () => {
    // Object.is tells 0 from -0.
    assert.ok(Object.is(roundHalfAway(x), want), `${name}: got ${roundHalfAway(x)}`);
  });
}

test("Math.round rounds a half toward +Infinity", () => {
  assert.equal(Math.round(2.5), 3);
  assert.ok(Object.is(Math.round(-2.5), -2));
  assert.ok(Object.is(Math.round(-0.4), -0));
});

test("toFixed rounds the binary value", () => {
  assert.equal((2.55).toFixed(1), "2.5");
  assert.equal((2.35).toFixed(1), "2.4");
});
round_half_away.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

// Math.round rounds a half toward +Infinity, so Math.round(-2.5) is -2.
// Round the magnitude, then set the sign. Adding 0 turns -0 into 0.
export function roundHalfAway(x: number): number {
  return Math.sign(x) * Math.round(Math.abs(x)) + 0;
}
round_half_away.test.ts 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.
import assert from "node:assert/strict";
import { test } from "node:test";

import { roundHalfAway } from "./round_half_away.ts";

const cases: [string, number, number][] = [
  ["down", 2.4, 2],
  ["up", 2.6, 3],
  ["negative", -2.6, -3],
  ["integer", 7.0, 7],
  ["half-even-up", 2.5, 3],
  ["half-odd-up", 1.5, 2],
  ["half-zero", 0.5, 1],
  ["half-negative", -2.5, -3],
  ["half-negative-small", -0.5, -1],
  ["negative-below-half", -0.4, 0],
  ["near-half", 0.49999999999999994, 0],
  ["zero", 0.0, 0],
  ["large-odd", 4503599627370497.0, 4503599627370497],
  ["large-half-negative", -1000000000000000.5, -1000000000000001],
];

for (const [name, x, want] of cases) {
  test(name, () => {
    // Object.is tells 0 from -0.
    assert.ok(Object.is(roundHalfAway(x), want), `${name}: got ${roundHalfAway(x)}`);
  });
}

test("Math.round rounds a half toward +Infinity", () => {
  assert.equal(Math.round(2.5), 3);
  assert.ok(Object.is(Math.round(-2.5), -2));
  assert.ok(Object.is(Math.round(-0.4), -0));
});

test("toFixed rounds the binary value", () => {
  assert.equal((2.55).toFixed(1), "2.5");
  assert.equal((2.35).toFixed(1), "2.4");
});
round_half_away.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

// Package rounding rounds a float to the nearest integer.
package rounding

import "math"

// RoundHalfAway rounds x to the nearest integer; a half goes away from zero.
// math.Round has this rule; math.RoundToEven rounds a half to the even integer.
func RoundHalfAway(x float64) int64 {
	return int64(math.Round(x))
}
round_half_away_test.go 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

package rounding

import (
	"math"
	"testing"
)

var cases = []struct {
	name string
	x    float64
	want int64
}{
	{"down", 2.4, 2},
	{"up", 2.6, 3},
	{"negative", -2.6, -3},
	{"integer", 7.0, 7},
	{"half-even-up", 2.5, 3},
	{"half-odd-up", 1.5, 2},
	{"half-zero", 0.5, 1},
	{"half-negative", -2.5, -3},
	{"half-negative-small", -0.5, -1},
	{"negative-below-half", -0.4, 0},
	{"near-half", 0.49999999999999994, 0},
	{"zero", 0.0, 0},
	{"large-odd", 4503599627370497.0, 4503599627370497},
	{"large-half-negative", -1000000000000000.5, -1000000000000001},
}

func TestRoundHalfAway(t *testing.T) {
	for _, c := range cases {
		if got := RoundHalfAway(c.x); got != c.want {
			t.Errorf("%s: got %d, want %d", c.name, got, c.want)
		}
	}
}

func TestRoundToEven(t *testing.T) {
	if got := math.RoundToEven(2.5); got != 2 {
		t.Errorf("RoundToEven(2.5) = %v", got)
	}
	if got := math.Floor(-2.5); got != -3 {
		t.Errorf("Floor(-2.5) = %v", got)
	}
	if got := math.Trunc(-2.5); got != -2 {
		t.Errorf("Trunc(-2.5) = %v", got)
	}
}
round_half_away.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

/// Rounds `x` to the nearest integer; a half goes away from zero.
/// `f64::round` has this rule; `f64::round_ties_even` rounds a half to the
/// even integer. The contract keeps `x` in the range of `i64`.
pub fn round_half_away(x: f64) -> i64 {
    x.round() as i64
}
tests/round_half_away_test.rs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/round-a-number/.

use algo_round_a_number::round_half_away;

#[test]
fn cases() {
    let cases: Vec<(&str, f64, i64)> = vec![
        ("down", 2.4, 2),
        ("up", 2.6, 3),
        ("negative", -2.6, -3),
        ("integer", 7.0, 7),
        ("half-even-up", 2.5, 3),
        ("half-odd-up", 1.5, 2),
        ("half-zero", 0.5, 1),
        ("half-negative", -2.5, -3),
        ("half-negative-small", -0.5, -1),
        ("negative-below-half", -0.4, 0),
        ("near-half", 0.49999999999999994, 0),
        ("zero", 0.0, 0),
        ("large-odd", 4503599627370497.0, 4503599627370497),
        ("large-half-negative", -1000000000000000.5, -1000000000000001),
    ];
    for (name, x, want) in cases {
        assert_eq!(round_half_away(x), want, "{name}");
    }
}

#[test]
fn library_modes() {
    assert_eq!(2.5_f64.round_ties_even(), 2.0);
    assert_eq!((-2.5_f64).floor(), -3.0);
    assert_eq!((-2.5_f64).trunc(), -2.0);
    assert_eq!((-2.5_f64).ceil(), -2.0);
}
round_half_away.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/round-a-number/.

# round_half_away X
# Prints the decimal text X rounded to the nearest integer; a half goes away
# from zero. Bash arithmetic has no floats, so the function reads the text:
# the integer part, then the first digit after the point.
round_half_away() {
  local x=$1 sign='' int frac=''
  if [[ $x == -* ]]; then
    sign=-
    x=${x#-}
  fi
  int=${x%%.*}
  [[ $x == *.* ]] && frac=${x#*.}
  # 10# reads the digits as decimal, so 010 is 10 and not octal 8.
  int=$((10#${int:-0}))
  if [[ ${frac:0:1} == [5-9] ]]; then
    int=$((int + 1))
  fi
  if ((int == 0)); then
    sign=''
  fi
  echo "$sign$int"
}
test_round_half_away.bats 31 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/round-a-number/.

setup() {
  source "$BATS_TEST_DIRNAME/round_half_away.sh"
}

check() { # check WANT X
  local got
  got=$(round_half_away "$2")
  [ "$got" = "$1" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$1"; return 1; }
}

@test "down" { check 2 2.4; }
@test "up" { check 3 2.6; }
@test "negative" { check -3 -2.6; }
@test "integer" { check 7 7.0; }
@test "half-even-up" { check 3 2.5; }
@test "half-odd-up" { check 2 1.5; }
@test "half-zero" { check 1 0.5; }
@test "half-negative" { check -3 -2.5; }
@test "half-negative-small" { check -1 -0.5; }
@test "negative-below-half" { check 0 -0.4; }
@test "near-half" { check 0 0.49999999999999994; }
@test "zero" { check 0 0.0; }
@test "large-odd" { check 4503599627370497 4503599627370497.0; }
@test "large-half-negative" { check -1000000000000001 -1000000000000000.5; }
@test "printf rounds a half to even" {
  [ "$(LC_ALL=C printf '%.0f %.0f' 2.5 3.5)" = "2 4" ]
}

References

  1. Math.Round Method, .NET API reference, Microsoft Learn, Overloads
  2. Built-in Functions, Python 3 documentation, round()
  3. math, Mathematical functions, Python 3 documentation, math.ceil, math.floor, math.trunc
  4. Math.round(), MDN Web Docs, Description
  5. Math.trunc(), MDN Web Docs, the introduction
  6. Number.prototype.toFixed(), MDN Web Docs, the introduction; Examples
  7. Math, Java SE 27 API, round(double), rint(double)
  8. RoundingMode, Java SE 27 API, Enum Constants
  9. round, lround, llround, C reference, cppreference.com, the description
  10. rint, lrint, llrint, C reference, cppreference.com, Notes
  11. printf, fprintf, sprintf, snprintf, C reference, cppreference.com, the conversion specifier f
  12. std::round, std::lround, std::llround, C++ reference, cppreference.com, the description
  13. math, Go standard library, func Round, func RoundToEven
  14. strconv, Go standard library, func FormatFloat
  15. f64, Rust standard library, round, round_ties_even
  16. std::fmt, Rust standard library, Precision
  17. Bash Reference Manual, version 5.3, 4.2 Bash Builtin Commands, printf

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source