Forum Moderators: open

Message Too Old, No Replies

js math and variable problem

         

indiguy

5:51 am on Oct 6, 2009 (gmt 0)

10+ Year Member



Cost = 0 , Grand_Total = 0, Product="";
function additem(Item_id, Price, Choice)
{
// var Choice = new Array();

if(Item_id.checked==true)
{
Cost = Cost++ + Price;
Cost = dollar(Cost);
Grand_Total = parseFloat(Cost);

Product = Product + Choice;
}

if(Item_id.checked==false)
{
Cost = Cost-- - Price;
Cost = dollar(Cost);
Grand_Total = parseFloat(Cost);
Choice=Choice.replace(/\+/g," ");
Product = Product - Choice;
}

document.order.GrandTotal.value = "$" + Grand_Total;
document.order.Cart.value = Product;
}
// format the dollar rounding of zeros
function dollar (amount)
{
amount = parseInt(amount * 100);
amount = parseFloat(amount/100);
if (((amount) == Math.floor(amount)) && ((amount - Math.floor (amount)) == 0))
{
amount = amount + ".00"
return amount;
}
if ( ((amount * 10) - Math.floor(amount * 10)) == 0)
{
amount = amount + "0";
return amount;
}
if ( ((amount * 100) - Math.floor(amount * 100)) == 0)
{
amount = amount;
return amount;
}
return amount;
}

This takes the price of a item and prints out the total.
Problem 1.
If current total from a couple of items are 6.90
when i remove an item $4.40
it totals $2.49 instead of $2.50 It will end up a -0.01 if i remove everything.

Problem 2.
Im passing the item names through the JS.
should that be an array?
I dont know how to print it out into the current page so they can see a list with the total. (no textbox wanted either as ive been testing with)

Can anyone help please... im no js expert.

tomda

6:13 am on Oct 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Problem 1 - Sorry, I am not a math guru... even less in js... but use alert() to debug your dollar function.

Problem 2 - An array would be better indeed, especialy if there are more than one items. But note that usually, when I deal with basket, I prefer to use raw text file using PHP, a tmp file that I create, update adn parse when necessary.

To print out JS result look for document.getElementById(containerid).innerHTML. As always, this is one alternative...

document.getElementById(containerid).innerHTML = '<b><i>This is my result:</i> '+amount+' USD</b>';

My 2 cents

rocknbil

7:20 pm on Oct 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



....it totals $2.49 instead of $2.50 It will end up a -0.01 if i remove everything.

Without testing your code, this is most likely a floating point precision issue, one that's driven me bonkers on occasion.

Here's a thread [webmasterworld.com] exploring the issue and some solutions.

The short story: toFixed() will resolve the one penny conundrum.