Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Quick Javascript Question

  • 04-01-2006 06:01PM
    #1
    Moderators, Science, Health & Environment Moderators Posts: 9,213 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,213 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