-1

i would like to format decimal values to specific format as like 1.23 should be shown as 0001.23 using javascript. is there any specific functions like toPrecision(), tofixed() in javascript to handle these kind of formatting or any pointers to go ahead with any solutions? here preceeding decimal is dynamic one. for example : i have 2 values : first value : 99.4545 second value : 100.32 in this second value has higher length (3)before decimal and first value has higher length after decimal(4). so subtracted result(0.8655) of this should be formatted as ###.#### (000.8685)

thank you

As k
  • 319
  • 5
  • 20
  • Duplicate of: http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript – David says reinstate Monica Nov 11 '13 at 23:06
  • Do yourself a favor, use a library, there are quite a few, e.g. https://npmjs.org/package/python-format, http://www.diveintojavascript.com/projects/javascript-sprintf – georg Nov 11 '13 at 23:19

3 Answers3

0

if you want to lpad some 0 onto 1.23 you can do the following

var value = 1.23

value = ("0000000"+ value).slice(-7);

Change the -7 to be whatever you want the total string length including the decimal point to be.

Added after question edit

The above should handle your question pre-edit but for the rest of it you'll need something like this.

var formatNum = function (num, preLen, postLen) {
  var value = num.split("."),
  padstring = "0";
  padLen = (preLen > postLen)?preLen:postLen;

  for (i = 0; i < padLen; i++) {
     padstring += padstring;
  }
  if (typeof(value[1]) === "undefined") {
    value[1] = "0";
  }

  return ((padstring + value[0]).slice(-preLen)+ "." + (value[1] + padstring).substring(0,postLen));
}

This takes the number you want formatted and the lengths you want each string to be on either side of the '.'. It also handles the case of an integer.

If you want it to output any other cases such as returning an integer, you'll have to add that in.

Diver
  • 1,480
  • 2
  • 17
  • 31
0

Just make a function that does what you want it to. Here is an example you can expand on if you want.

function pad(num, padSize){
  var numString = "" + num.split('.')[0];
  if(num.length < padSize){
    var numZeroes = padSize-num.length;
    var zeroes = "";
    while(numZeroes){zeroes += "0"; numZeroes--;}
    return zeroes + num;
  }else return num;
}
posit labs
  • 7,733
  • 4
  • 32
  • 57
-2

Try to use a string, like "000" + some value