1

I'd like to display numerical information to users in a flexible way. toFixed and toPrecision always pad with zeros, which is undesirable. Ideally, I would be able to express that:

  • 5.450000000001 should be displayed as "5.45"
  • 6.0 should be displayed as "6"
  • 5.45001 should be displayed as "5.45001", but I'd also like to explicitly say "use no more than 2 decimal places", in which case this should be displayed as "5.45".

Are there good JS libraries for displaying numbers this way? If not, is there a good library in some other language that I can translate?

2
  • If I understand correctly, you want two decimal spaces unless the number ends in a 0. If it ends in a 0 you want the remove the trailing 0. Right? Commented Sep 11, 2013 at 23:43
  • 2
    Check numeraljs.com Commented Sep 11, 2013 at 23:43

1 Answer 1

2

You probably don't need a whole library for this one purpose. For example, you could just use toFixed(2) and then strip trailing 0s and a trailing decimal point:

function format_number(x){
  return ((+x).toFixed(2)+'').replace(/\.?0*$/, '');
}

Usage:

format_number(5.450000000001); // "5.45"
format_number("6.0"); // "6"
format_number("5.45001"); // "5.45"

It would be easy to accept the maximum number of decimal points as an optional argument too:

function format_number(x, digits){
  if(typeof digits != 'number')
    digits = 2;
  return ((+x).toFixed(digits)+'').replace(/\.?0*$/, '');
}

format_number(5.45001); // "5.45"
format_number(5.45001, 5); // "5.45001"
Sign up to request clarification or add additional context in comments.

3 Comments

Could the downvoter kindly leave a comment, so that I can improve my answer?
Here's a way to do it with one regex: jsbin.com/oTUpUXI/1/edit. Seems to work fine, but may need some adjustments.
316245753745765473542543257.toFixed(4) // => '3.162457537457655e+26'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.