Skip to main content
@spa-tools/utilities

roundToNearest()

Have you ever needed to round a number without having it returned as a formatted string? Beyond having to figure out when to use which, both toPrecision() and toFixed() return a string. And while Math.round() returns a number, it only rounds to the nearest whole number, effectively returning an integer.

This is where roundToNearest() comes in to save the day by rounding a number to the nearest specified number of decimal places while still returning a number.

Usage

import { roundToNearest } from '@spa-tools/utilities';

const roundedNumber1 = roundToNearest(1.2345, 2);
console.log(roundedNumber1);
// --> 1.23

const roundedNumber2 = roundToNearest(1.2345, 3);
console.log(roundedNumber2);
// --> 1.235

Arguments

NameTypeRequired?DefaultDescription
numnumberyes-The number to round
decimalPlacesnumberno0The decimal places to round to

Returns

Returns rounded number as a number.