Precision
Rounding numerical values.
In-built
Useful in-built JS functions for rounding numbers
// Round up or downMath.ceil(2.5); // 3Math.floor(2.5); // 2
// Round to closest integerMath.round(2.5); // 3
When converting a number to a string (for printing out, for example) you can also round:
// Print Pi to 2 digitsMath.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 placesround(2, Math.PI); // 3.14
// Make a reusable function that rounds to 2 decimal placesconst 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 10quantiseEvery(11, 10); // 10quantiseEvery(25, 10); // 30
// Round to nearest decimal with 0.1quantiseEvery(1.123, 0.1); // 1.1quantiseEvery(1.19, 0.1); // 1.2