0

I'm trying to format a variable to have a specific format 0000.00 currently my variable is be returned as 1.00 and want to get 0001.00

Any help would be greatly appreciated!

philecker
  • 49
  • 1
  • 7

3 Answers3

1

Here is a really short function to do what you want:

function formatNum(num) {
    return ('0000'+num.toFixed(2)).slice(-7);
}

Demo: http://jsfiddle.net/DuZqk/

Jeff B
  • 29,943
  • 7
  • 61
  • 90
0

I touched on this topic once and have this function laying around. Perhaps that is of use for you. Just call the function with your number and the digits you want.

 function pad(num, digits) {
     var padding = '';
     var numdigits = num.toString();
     var parts = numdigits.split(".");

     if (parts[1].length < 2) {
         numdigits = numdigits + "0";
     }

     if (numdigits.length > digits) {
         warning("length number is longer than requested digits");
         return;
     } else {
         for (var i = 0; i < digits; i++) {
             padding += "0";
         }
         var numstr = padding + numdigits;
         numstr = numstr.substr(numdigits.length);
         return numstr;
     }

 }

call:

pad(1.50, 6);

result "001.50"

fiddle: http://jsfiddle.net/djwave28/gKs3U/8/

Daniel
  • 4,816
  • 3
  • 27
  • 31
  • Thank you, I will give this a try. I think this will do exactly what I wanted! – philecker Apr 04 '13 at 00:51
  • Put it in a fiddle, so you can play with it. – Daniel Apr 04 '13 at 00:53
  • This is exactly what I wanted, only issue I'm having is if mynumber = 1.50, I get 00001.5 versus 0001.50 but if I change it to mynumber = 1.55 I get the expected result 0001.55 – philecker Apr 04 '13 at 01:06
  • Simply test for the characters behind the dot after teh toString method. If it is smaller than 2, then rewrite the string back to its original by adding the "zero" to it again. Teh code is adjusted including the fiddle. – Daniel Apr 04 '13 at 03:47
0

I use a similar method for integers, but i assume you are dealing with a string as javascript return 1.00 as 1

function pad(num, size) {
    var f=num.split(".");
    while (f[0].length < size) f[0] = "0" + f[0];
    return f[0]+f[1];
}
Bakly
  • 640
  • 6
  • 18