@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
Name | Type | Required? | Default | Description |
---|---|---|---|---|
num | number | yes | - | The number to round |
decimalPlaces | number | no | 0 | The decimal places to round to |
Returns
Returns rounded number as a number
.