Calling roundTo(103.35, 0.1) gives 103.30000000000001 where it should give 103.4.
Original function:
/** Round a number `n` to the nearest multiple of `increment`. */
export function roundTo(n: number, increment = 1) {
return Math.round(n / increment) * increment;
}
This function looks to work properly:
function roundTo(n: number, increment = 1) {
const v1 = Math.round(n / increment ) * increment
const v2 = Math.round(n / increment + 1e-10) * increment
const v3 = Math.round(n / increment - 1e-10) * increment
return Math.abs(v1 - v2) > increment / 10 ? v2 : v3
}
Calling
roundTo(103.35, 0.1)gives103.30000000000001where it should give103.4.Original function:
This function looks to work properly: