help with simple javascript
Go to solution
Solved by mariushm,
Something like this, with proper rounding to 2 decimals
<!DOCTYPE html> <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <div data-ng-app="" data-ng-init="Weight=0; quantity=0; price=0"> <form> <input id="price" ng-model="price" type="text" placeholder="price"> <br><br> <input id="Weight" type="text" placeholder="weight"> <br><br> <input id="quantity" type="text" placeholder="quantity"> <br> comission <p id="comm"> </p> shipping <p id="ship"> </p> total <p id="tot"> </p> <br><br> <script type="text/javascript"> function myFunction() { var price = parseFloat(document.getElementById("price").value); var weight = parseFloat(document.getElementById("Weight").value); var qty = parseFloat(document.getElementById("quantity").value); var comm = 0 console.log(price, weight, qty) if (price <= 100) { comm = 3 } else { comm = 0.035 * price } var ship = 7 * weight var tot = qty * (ship + comm + price) console.log(comm, ship, tot) var comm_rounded = Math.round(comm*100 + Number.EPSILON)/100 var total_rounded = Math.round(tot*100 + Number.EPSILON)/100 document.getElementById("comm").innerHTML = comm_rounded document.getElementById("ship").innerHTML = ship; document.getElementById("tot").innerHTML = total_rounded } </script> <button class="btn cyan waves-effect waves-light" onclick="myFunction()">Calculate</button> </form> </body> </html>
If you'll accept weight as floating point and not just multiple of kg, then you may want to round that up as well. And you may want to calculate the total as quantity x ( rounded to 2 decimals for all three) because otherwise you may have a situation where there's a difference in numbers of a few pennies caused by the rounding at the end.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now