Skip to content

roundTo is probably wrong #33

@dk-teknologisk-osv

Description

@dk-teknologisk-osv

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions