Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Quick Javascript Question

  • 04-01-2006 5:01pm
    #1
    Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭


    O.k. I grab a number from a texbox that a user has entered and parse it as an int into a var. Then I grab a unit price from a hidden field and parse it as a float into a var. So in calculating the price I multiply the cost * the amount the user has entered but can someone tell me why when it multiplies 1.20 by 3 for example it winds up with 3.5999999999999996 and with other multiples it seems fine?

    [php]
    function Recalc() {
    var totalcost = document.getElementById("totcost");
    var currcost = 0;
    var x = document.getElementsByTagName("input");
    for (i=0;i<x.length;i++) {
    if (x.id.indexOf("ItemAmount")>-1) {
    var amtobj = document.getElementById(x.id);
    var objcost = document.getElementById(x.id.replace("ItemAmount", "ItemCost"));
    var cost = parseFloat(objcost.value);
    var amt = parseInt(amtobj.value);
    currcost+=(amt*cost);
    }
    }
    if (currcost>=0) {
    totalcost.innerHTML=currcost;
    }
    }[/php]


Comments

  • Closed Accounts Posts: 2,046 ✭✭✭democrates


    That's down to the vagaries of floats, happens in many languages.
    How about doing calculations in cent to avoid floats and just use int vars?
    If this is not feasible (eg vat calculations etc) just round the results of calculations to two decimal places.
    PS, I take it you're cleansing all user input, hidden fields are easily altered on the client.


  • Moderators, Science, Health & Environment Moderators Posts: 9,035 Mod ✭✭✭✭mewso


    Yeah used toFixed to round it. This is an Intranet app and trust me they wouldn't have a clue about altering hidden fields. If it was external I would be more concerned with security. Thanks.


Advertisement