Forums: How to format numbers in Javascript - Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to format numbers in Javascript

#1 User is offline   admin 

  • Administrator
  • PipPipPip
  • Group: Admin
  • Posts: 16044
  • Joined: 03-February 03

Posted 19 November 2013 - 09:29 PM

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

Best regards,
Sergey Kornilov
0

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic