Skip to content

Precision

Rounding numerical values.

In-built

Useful in-built JS functions for rounding numbers

// Round up or down
Math.ceil(2.5); // 3
Math.floor(2.5); // 2
// Round to closest integer
Math.round(2.5); // 3

When converting a number to a string (for printing out, for example) you can also round:

// Print Pi to 2 digits
Math.PI.toFixed(2); // "3.14"

A cheeky way of rounding to a desired number of digits is by converting to a string and then back again:

let p = Number.parseFloat(Math.PI.toFixed(2)); // 3.14

Decimal places

ixfx has Numbers.round

import { round } from 'https://unpkg.com/ixfx/dist/numbers.js';
// Round Pi to 2 decimal places
round(2, Math.PI); // 3.14
// Make a reusable function that rounds to 2 decimal places
const r = round(2);
r(Math.PI); // 3.14

Quantise

Quantising rounds a number to a given step size. Numbers.quantiseEvery

import { quantiseEvery } from 'https://unpkg.com/ixfx/dist/numbers.js';
// Round numbers to nearest multiple of 10
quantiseEvery(11, 10); // 10
quantiseEvery(25, 10); // 30
// Round to nearest decimal with 0.1
quantiseEvery(1.123, 0.1); // 1.1
quantiseEvery(1.19, 0.1); // 1.2