The CreatorCon Call for Content is officially open! Get started here.

ParseFloat stops calculating a decimal properly once it goes to a decimal point

SC10
Kilo Guru

I am a using a parseFloat to attempt to calculate two decimal fields, however once one of the two fields goes from 999 to 1,000, the calculation breaks.

My scripts:

function calculatetotalcosts() {

  var labour = parseFloat(g_form.getValue('u_estimateditlabourcosts'));

  var serviceandmaterials = parseFloat(g_form.getValue('u_estimatedserviceandmaterialscosts'));

  var result = labour + serviceandmaterials;

  g_form.setValue('u_estimatedtotalcosts',result);

}

Good calculation:

10 + 10 = 20

http://i.imgur.com/wxljW2F.png

Bad calculation:

1000 + 10 = 11

http://i.imgur.com/It06NTg.png

Looks to be that once it hits a decimal, it drops the zeroes and just sees the number before the decimal, 1 + 10 = 11.

Any suggestions?

1 ACCEPTED SOLUTION

edwin_munoz
Mega Guru

Helo Shane,



Most probably there is a comma in the string. Try it like this


  1. function calculatetotalcosts() {  
  2.   var labour = parseFloat(g_form.getValue('u_estimateditlabourcosts').replace(/,/g,''));  
  3.   var serviceandmaterials = parseFloat(g_form.getValue('u_estimatedserviceandmaterialscosts').replace(/,/g,''));  
  4.   var result = labour + serviceandmaterials;  
  5.   g_form.setValue('u_estimatedtotalcosts',result);  
  6. }  

View solution in original post

6 REPLIES 6

Edwin Munoz



I noticed that the end product being calculated inserts without the commas, and it has come back to me now that retaining the commas is important (as this is ultimately calculation a cost amount).



Trying to change the values to a comma instead of blank (as per your original script) re-introduces my original issue of the calculation breaking at the comma point of the field:



function calculatetotalcosts() {


  var labour = parseFloat(g_form.getValue('u_estimateditlabourcosts').replace(/,/g,','));


  var serviceandmaterials = parseFloat(g_form.getValue('u_estimatedserviceandmaterialscosts').replace(/,/g,','));


  var result = labour + serviceandmaterials;


  g_form.setValue('u_estimatedtotalcosts',result);


}


As a follow up to my previous post from today, I was able to get this working with the following script:



function calculatetotalcosts() {


var labour = parseFloat(g_form.getValue('u_estimateditlabourcosts').replace(/,/g,''));


if (isNaN(labour)) {


labour = 0;


}


var serviceandmaterials = parseFloat(g_form.getValue('u_estimatedserviceandmaterialscosts').replace(/,/g,''));


if (isNaN(serviceandmaterials)) {


serviceandmaterials = 0;


}


var result = labour + serviceandmaterials;


g_form.setValue('u_estimatedtotalcosts',numberWithCommas(result.toFixed(2)));


}



function numberWithCommas(x) {


x = x.toString();


var pattern = /(-?\d+)(\d{3})/;


while (pattern.test(x))


x = x.replace(pattern, "$1,$2");


return x;


}