jquery - Calculate price with decimals -


i working on script calculate price surface, 'm2'. below script, want euros 2 decimals. how can fix this. have tried parsefloat() , tofixed(2) think it's not past in right place. hope can me out.

var surface; var totalprice;  function calculatesurface() {     var length = document.getelementbyid("length").value;     var width = document.getelementbyid("width").value;      surface = length * width; }    function calculateprice() {     var area = $('#area').val();      if(area=='pur3') {         totalprice = surface * 16;     }      else if(area=='pur4') {         totalprice = surface * 17.50;     }      else if(area=='pur5') {         totalprice = surface * 19;     }      else if(area=='pur6') {         totalprice = surface * 21;     }      else if(area=='pur7') {         totalprice = surface * 23.50;     }  }  function showresults() {     return surface + '  ' + totalprice; }   $("#calc").click(function(e) {     e.preventdefault();     calculatesurface();     calculateprice();        $('.result').html('aantal oppervlakte: ' + surface + ' m&sup2;' + '<br>' + '&euro; ' + totalprice + '' );  }); 

like said, should round when printing anything. keep real calculation values @ times avoid loss of precision. in fact, when saving data, should save parameters , not results, can recalculate raw arguments if needs be.

here's jsfiddle example :

var areabaseprice = {   'pur3': 16,   'pur4': 17.50,   'pur5': 19,   'pur6': 21,   'pur7': 23.5 };  function calculatesurface() {   var length = $("#length").val();   var width = $("#width").val();    return length * width; }   function calculateprice() {   var area = $('#area').val();    return areabaseprice[area] * calculatesurface(); }  $("#calc").click(function(e) {     var surface = calculatesurface();     var price = calculateprice();      $('.result').html('aantal oppervlakte: ' + surface + ' m&sup2;' + '<br>' + '&euro; ' + price.tofixed(2) );      e.preventdefault(); }); 

edit

just note on loss of precision floating values. unless working banking company many critical transactions, should really not concerned rounding hundreth of value (up or down). if do, send parameters server side and/or use proper currency manipulation library needs.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -