Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  87] [ 3]  / answers: 1 / hits: 103647  / 13 Years ago, fri, august 12, 2011, 12:00:00

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.


More From » jquery

 Answers
7

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

[#90651] Thursday, August 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriea

Total Points: 641
Total Questions: 118
Total Answers: 101

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
;