I'm building a fairly calculation-heavy cart for a fabric store and have found myself needing to do a calculation on user inputted length * the baseprice per metre, but then checking the result to see if it is a multiple of the pattern length. If it is not a multiple, I need to find the closest multiple of the pattern length and change the result to that.
I need to also be able to do exactly the same calculation in PHP, but if anyone can help me out with the maths I can port anything that needs to be translated myself.
I am using jQuery 1.6.2 and already have the first part of the calculation done, I just need to check the result of (metres*price) against the pattern length.
Any help greatly appreciated
EDIT: These calculations all involve 2 decimal places for both the price and the pattern length. User inputted length may also contain decimals.
When one number can be divided by another number with no remainder, we say the first number is divisible by the other number. For example, 20 is divisible by 4 ( ). If a number is divisible by another number, it is also a multiple of that number. For example, 20 is divisible by 4, so 20 is a multiple of 4.
Use the modulus operator: if (num % 5 == 0) //the number is a multiple of 5.
A multiple of a number should be able to divided by the initial number you are seeking the multiple for without any remainder. For example, 8 is a multiple of 2, and as 2 * 4 = 8, therefore 8/2 = 4. In this example, 2 and 4 are also factors of 8 and there are no remainders left. Compare this to dividing 12 by 5.
Use the %
(modulus) operator in Javascript and PHP, which returns the remainder when a
is divided by b
in a % b
. The remainder will be zero when a
is a multiple of b
.
Ex.
//Javascript var result = userLength * basePrice; //Get result if(result % patternLength){ //Check if there is a remainder var remainder = result % patternLength; //Get remainder if(remainder >= patternLength / 2) //If the remainder is larger than half of patternLength, then go up to the next mulitple result += patternLength - remainder; else //Else - subtract the remainder to go down result -= remainder; } result = Math.round(result * 100) / 100; //Round to 2 decimal places
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With