0

I do NOT want to round to the NEAREST 0.5. I want to round DOWN to the nearest 0.5 value.

I have a function from excel that I use: =FLOOR(value,0.5)

9.55 becomes 9.5 9.99 becomes 9.5 9.2 becomes 9

Etc.

Is there an equivalent in javascript? I know that Math.floor () will round down to the nearest integer. However, does anyone know of a good way to round down to the nearest 0.5 instead?

Thank you in advance

1 Answers1

1

Return the whole number + 0.5, if the original decimal value is >= 0.5.

const floor = (value) => {
  let wholeNumber = Math.floor(value)
  return wholeNumber + ((value - wholeNumber) < 0.5 ? 0.0 : 0.5)
}

This can be modified to support nearly any fraction other than 0.5.

const assertEquals = (n1, n2, precision = 0.001) => Math.abs(n1 - n2) <= precision

/**
 * Returns the largest integer less than or equal to a given number rounded down to the nearest fraction.
 * @param {number} value - A positive floating-point value
 * @param {number} [nearest=1.0] - A fractional value between (0.0, 1.0]
 * @return A number representing the largest integer less than or equal to the specified number rounded down to the nearest fraction
 */
const floorNearest = (value, nearest = 1.0) => {
  let wholeNumber = Math.floor(value)
  let fraction = value - wholeNumber
  let factor = Math.floor(fraction / nearest)
  return wholeNumber + (nearest * factor)
}

console.log(assertEquals(floorNearest(1.50), 1))
console.log(assertEquals(floorNearest(1.25), 1))

console.log(assertEquals(floorNearest(9.55, 0.5), 9.5))
console.log(assertEquals(floorNearest(9.99, 0.5), 9.5))
console.log(assertEquals(floorNearest(9.20, 0.5), 9.0))

console.log(assertEquals(floorNearest(0.55, 0.200), 0.400))
console.log(assertEquals(floorNearest(0.55, 0.250), 0.500))
console.log(assertEquals(floorNearest(0.99, 0.333), 0.666))
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132