Precision
Rounding numerical values.
In-built
Section titled “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
Section titled “Decimal places”ixfx has Numbers.round
import { Numbers } from 'https://unpkg.com/@ixfx/bundle';
// Round Pi to 2 decimal placesNumbers.round(2, Math.PI); // 3.14
// Make a reusable function that rounds to 2 decimal placesconst r = Numbers.round(2);r(Math.PI); // 3.14
Quantise
Section titled “Quantise”Quantising rounds a number to a given step size. Numbers.quantiseEvery
import { Numbers } from 'https://unpkg.com/@ixfx/bundle';
// Round numbers to nearest multiple of 10Numbers.quantiseEvery(11, 10); // 10Numbers.quantiseEvery(25, 10); // 30
// Round to nearest decimal with 0.1Numbers.quantiseEvery(1.123, 0.1); // 1.1Numbers.quantiseEvery(1.19, 0.1); // 1.2