homepage Welcome to WebmasterWorld Guest from 54.237.78.165
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
why does adding three numbers result in a string?
nelsonm

5+ Year Member



 
Msg#: 4459253 posted 12:41 am on May 30, 2012 (gmt 0)

Hi all,

this is pretty weird... I have this javascript code to add some floating point numbers as follows:

var subtotal = 0.00, salestax = 0.00, taxrate = 0.00, surcharge = 0.00, salestotal = 0.00;

// get each item cost and calculate subtotal.
$('#workorder-form #sa-table-1 tbody tr input[name="wi-Cost"]').each(function (){if($(this).val() != ''){subtotal += parseFloat($(this).val());}});

// calculate surcharge.
if(subtotal == 0.00){surcharge = 0.00;}else if(subtotal <= 100.00){surcharge = 5.00;}else{surcharge = subtotal * 0.06;} // gas surcharge calculation.

taxrate = 0.00;

subtotal = (subtotal).toFixed(2);
salestax = (subtotal * (taxrate / 100)).toFixed(2);
taxrate = (taxrate).toFixed(2);
surcharge = (surcharge).toFixed(2);
salestotal = (subtotal + salestax + surcharge); //.toFixed(2);

console.log('subtotal: ',isNaN(subtotal),', salestax: ',isNaN(salestax),',taxrate: ',isNaN(taxrate),',surcharge: ',isNaN(surcharge),',salestotal: ',salestotal);

The console.log shows that all the variables but "salestotal" are numbers!

How can adding three numbers result in a string of the three numbers?

 

Fotiman

WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member



 
Msg#: 4459253 posted 1:21 am on May 30, 2012 (gmt 0)

toFixed returns a string representation of the number. So at the time you call toFixed on them, they should all be getting changed to strings.

nelsonm

5+ Year Member



 
Msg#: 4459253 posted 2:17 am on May 30, 2012 (gmt 0)

so, is the correct way to handle the math as follows?

subtotal = (subtotal).toFixed(2);
salestax = (parseFloat(subtotal) * (parseFloat(taxrate) / 100)).toFixed(2);
taxrate = (taxrate).toFixed(2);
surcharge = (surcharge).toFixed(2);
salestotal = (parseFloat(subtotal) + parseFloat(salestax) + parseFloat(surcharge)).toFixed(2);


// fill sales total fields. all totals set to 2 decimal places.
$('#workorder-form input#wo-SubTotal' ).val(subtotal);
$('#workorder-form input#wo-SalesTax' ).val(salestax);
$('#workorder-form label#wo-TaxRate' ).text(taxrate+'%');
$('#workorder-form input#wo-SurCharge' ).val(surcharge);
$('#workorder-form input#wo-SalesTotal').val(salestotal);

Fotiman

WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member



 
Msg#: 4459253 posted 3:49 am on May 30, 2012 (gmt 0)

You probably shouldn't be relying on JavaScript to do these calculations. These should be calculated server-side because toFixed may give different results in different browsers.

If you're going to do it with JavaScript, then don't call toFixed until you're ready to display the value. That is, don't call toFixed, then parseFloat on that value.

nelsonm

5+ Year Member



 
Msg#: 4459253 posted 12:43 pm on May 30, 2012 (gmt 0)

You probably shouldn't be relying on JavaScript to do these calculations.

Yea... I'm discovering that javascript can be a little tricky with math.

toFixed may give different results in different browsers.

really?! Is there an example of this?

I do agree that you should hold off using toFixed until your ready to display the data. I will fix that until i rewrite my php totals script so it's able to b e called from the javascript.

thanks.

[edited by: nelsonm at 1:33 pm (utc) on May 30, 2012]

nelsonm

5+ Year Member



 
Msg#: 4459253 posted 12:57 pm on May 30, 2012 (gmt 0)

Thanks to you and daveVk... I was able to get my code not only working but working better.

You and daveVk have saved me many hours of "hair pulling" frustration! And just to let you all know, i don't just take your answers and run... I also subsequently do more research on the solutions you offer such as "closures". One article is: [url]https://developer.mozilla.org/en/JavaScript/Guide/Closures[/url] . I have since read articles on the topic - several times - and while it's still a little fuzzy, i understand it enough so that in most situations, i know when to use it.

Here is the code you helped get working and improve:

function recalcTotals(){
var subtotal = 0.00, salestax = 0.00, taxrate = 0.00, surcharge = 0.00, salestotal = 0.00;
var taxEnabled = true, data, sdata;

// get each item cost and calculate subtotal.
$('#workorder-form #sa-table-1 tbody tr input[name="wi-Cost"]').each(function (){if($(this).val() != ''){subtotal += parseFloat($(this).val());}});

// calculate surcharge.
if(subtotal == 0.00){surcharge = 0.00;}else if(subtotal <= 100.00){surcharge = 5.00;}else{surcharge = subtotal * 0.06;} // gas surcharge calculation.

var updateForm = function() {
salestax = subtotal * (taxrate / 100);
salestotal = subtotal + salestax + surcharge;


// fill sales total fields. set all totals to 2 decimal places.
$('#workorder-form input#wo-SubTotal' ).val(subtotal.toFixed(2));
$('#workorder-form input#wo-SalesTax' ).val(salestax.toFixed(2));
$('#workorder-form label#wo-TaxRate' ).text(taxrate.toFixed(2)+'%');
$('#workorder-form input#wo-SurCharge' ).val(surcharge.toFixed(2));
$('#workorder-form input#wo-SalesTotal').val(salestotal.toFixed(2));
};


if(taxEnabled) {
data = {'_search':true, filters: '{"groupOp":"AND","rules":[{"field":"st.StateAbbrev","op":"eq","data":"'+$('#workorder-form select#cu-STID option:selected').text()+'"}]}', page:1, rows:40, searchField:'', searchOper:'', searchString:'', sidx:'st.StateAbbrev', sord:'asc'};
$.post('php/statetab-script.php', data, function(sdata){
var response = JSON.parse(sdata);
var row = response.rows['0'];
taxrate = parseFloat(row['cell']['4']);
updateForm();

});

}else{
updateForm();
}

}



again, thanks a lot.

[edited by: nelsonm at 1:52 pm (utc) on May 30, 2012]

Fotiman

WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member



 
Msg#: 4459253 posted 1:50 pm on May 30, 2012 (gmt 0)


You probably shouldn't be relying on JavaScript to do these calculations.


Yea... I'm discovering that javascript can be a little tricky with math.

It can be a little tricky with floating point math. However, that's true of any language. The reason to do the math server side, though, is that then you'll always get the same result, whereas doing it client side means you could get one result for a particular browser and a different result for another browser.


toFixed may give different results in different browsers.


really?! Is there an example of this?

// In Internet Explorer 8 and older, this produces '0'
// while in IE9, Firefox, or Chrome this produces '1'
document.write((0.947).toFixed(0));

nelsonm

5+ Year Member



 
Msg#: 4459253 posted 1:56 pm on May 30, 2012 (gmt 0)

ok... i'm convinced. I'll fix my code to call a php totals script asap.

thanks.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved