8
\$\begingroup\$

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.

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

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
*/
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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