Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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 => 14.00
    14.1 => 14.10
    14.123 => 14.123
    14.12347 => 14.1234
    

I don't want rounding to happen

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

Help me improve on this.

share|improve this question
2  
As I interpret it, 14.99999 → '14.9999' –  200_success Jan 26 '14 at 17:53
2  
toString().split('.') isn't going to work reliably. Consider that some cultures write their numbers using a comma for a decimal 987,24 –  George Mauer Jan 27 '14 at 1:39
    
@kleinfreund Right –  Vjy Jan 27 '14 at 13:04
    
@200_success Correct –  Vjy Jan 27 '14 at 13:05

1 Answer 1

up vote 2 down vote accepted

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 <=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 => 14.00
14.1 => 14.10
14.123 => 14.123
14.12347 => 14.1234
*/
share|improve this answer
    
Perfect, will try this now. Thanks –  Vjy Jan 27 '14 at 13:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.