How to *correctly* round to the nearest multiple

589 Views Asked by At

I am struggling to find the correct implementation for rounding to the nearest multiple. I thought the simple arithmetic of [number/multiple]*multiple would give me my solution but I am running into instances where this is false. I am trying to mimic Excel's MROUND function.

Given the number 422.3710249 and the multiple .00125, I receive a number that is off by a certain level of precision... see javascript example to get the number.

console.log(Math.round(422.3710249/.00125)*.00125) = 422.37125000000003

Where my solution faulty? I expect this: 422.37125


1

There are 1 best solutions below

1
On BEST ANSWER

Remember that floating point numbers are not able to represent any real number. You are getting the right result using floating point arithmetic. The closest number to $422.37125$ the computer can represent using floats is $422.37125000000003$.