This topic is locked

How to format numbers in Javascript

11/19/2013 4:29:39 PM
ASPRunnerPro Tips and tricks
admin

Question:

Using the "Javascript OnLoad Event" on an edit page.
My calculation code is:

function func() {

ctrlBodyTechGP.setValue(Number(ctrlBodyTechRetail.getValue()) - Number(ctrlBodyTechCost.getValue())) ;

ctrlBodyTechGPP.setValue((Number(ctrlBodyTechRetail.getValue()) - Number(ctrlBodyTechCost.getValue())) / Number(ctrlBodyTechRetail.getValue ())*100) ;

};


Which gives me a Gross Profit Percentage but my format on the page is like 31.1211211. I would like it to be 31.1.
Answer:

The best option is to use toFixed() function.

function func() {

var va1 = Number(ctrlBodyTechRetail.getValue()) - Number(ctrlBodyTechCost.getValue());

ctrlBodyTechGP.setValue(val1.toFixed(1));

var val2 = (Number(ctrlBodyTechRetail.getValue()) - Number(ctrlBodyTechCost.getValue())) / Number(ctrlBodyTechRetail.getValue ())*100;

ctrlBodyTechGPP.setValue(val2.toFixed(1));

};


Examples of toFixed() function usage:

var numObj = 12345.6789;
numObj.toFixed(); // Returns "12346": note rounding, no fractional part
numObj.toFixed(1); // Returns "12345.7": note rounding
numObj.toFixed(6); // Returns "12345.678900": note added zeros