0

First of all I'm not sure if "multiple" is the right term to use in my question. But here is my situation. I am building a shop that accepts orders by quarters of 1/4(.25) or 1/2(.5), like buying 1.5kg of rice or 1/4kg of garlic, etc. Now, when someone places an order, how do I correctly check if the quantity that he input is a multiple of that quarter.

So, for example I only accept orders by 1/4 (.25 in decimal), the input and result should be the ff:

.5 (good)

.75 (good)

1.25 (good)

.8 (bad)

1.33 (bad)

Right now, I just divide the input by the quarter. Then, if the answer is a whole number, it's considered good.

Is it the right way to do it?

Thanks!

Epic Martijn
  • 335
  • 2
  • 12
noob101
  • 3
  • 2
  • [javascript how to tell if one number is a multiple of another](https://stackoverflow.com/questions/7037926/javascript-how-to-tell-if-one-number-is-a-multiple-of-another) – Andreas Jul 30 '20 at 12:18
  • Don't just make this check on the client. Also validate the input on the server! – Andreas Jul 30 '20 at 12:19
  • Does this answer your question? [javascript how to tell if one number is a multiple of another](https://stackoverflow.com/questions/7037926/javascript-how-to-tell-if-one-number-is-a-multiple-of-another) – Ace Jul 30 '20 at 12:21

2 Answers2

2

It's a valid solution, but i'd suggest to use the modulus operator (%), like this:

const isValid = amount % 0.25 === 0;
nip
  • 1,609
  • 10
  • 20
  • 49.90 % 0.10 = 0.09999999999999581 see this [post](https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript) – glinda93 Jul 30 '20 at 12:25
0

Due to known javascript precision problems, using modulus operator on floats is not a good idea.

Instead, you can multiply the numbers by 100 to make them integers and check.

For example:

const isValid = (amount) => {
  return (amount * 100) % 25 === 0
}

console.log(isValid(0.5));
console.log(isValid(0.25));
console.log(isValid(1.25));
console.log(isValid(0.1));
console.log(isValid(0.33));

Posts related to JS precision problems:

glinda93
  • 7,659
  • 5
  • 40
  • 78