Skip to content

roundTo is probably wrong #33

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
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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