Number format in JavaScript What's the best way to format a number?


If decimal is less than 2 digits, add zero to make it 2 decimals
If more than 4, truncate to 4 decimals
If 3 decimals, keep it to 3 decimals

14 =&gt; 14.00
14.1 =&gt; 14.10
14.123 =&gt; 14.123
14.12347 =&gt; 14.1234



I don't want rounding to happen

if (number !== 0) {
    nParts = number.toString().split('.');
    if (nParts[1]) {
      if (nParts[1].length &gt; 4) {
        nParts = 4;
      } else if (nParts[1].length &lt; 3) {
        nParts = 2;
      } else {
        nParts = 3;
      }
    } else {
      nParts = 2;
    }
} 
number = number.toFixed(nParts);


Help me improve on this.
since you don't want rounding, treat as string rather than number...    

function strange(number){
    var n=0;
    if (number !== 0) {
        nParts = number.toString().split(/\.|,/);
        if (nParts[1]){
            n=nParts[1].length;
            n = n &lt;=2 ? 2 : n==3 ? 3 : 4;
            nParts[1] = nParts[1] + '0'
        }else{
            n=2;
            nParts[1]='00';
        }
    } 
    return nParts[0] + '.' + nParts[1].slice(0,n);
}

;strange(14);
;strange(14.1);
;strange(14.123);
;strange(14.12347);

/*
14 =&gt; 14.00
14.1 =&gt; 14.10
14.123 =&gt; 14.123
14.12347 =&gt; 14.1234
*/