Sensei Sensei - 7 days ago 5
Javascript Question

Round to minimum of 2 decimals and max of 4 decimals in Javascript

Is there a way to round number to min 2 decimals i javascript.

Example:


  1. 10 -> 10.00

  2. 20.10 -> 20.10

  3. 30.1234 -> 30.1234

  4. 40.123456 -> 40.1235

  5. 50.1200 -> 50.12

  6. 60.123 -> 60.123



And so on... so round to min 2 decimals. I can use jquery for this.

Answer

It sounds like you're saying you want to turn numbers into strings with at least two decimal places (even if they're zeros) and up to four if necessary (they aren't zeros). If so:

For all modern browsers: See Marek's answer.

If you can't rely on Intl: The only thing I can think of is to use toFixed(4) and then remove up to two trailing zeros:

function format(num) {
  var str = num.toFixed(4);
  return str.replace(/0{1,2}$/, '');
}
function test(test) {
  var result = format(test.num);
  console.log(
    test.num,
    "=>",
    result,
    result == test.result ? "- Pass" : "- Fail"
  );
}

[
    {num: 10, result:  "10.00"},
    {num: 20.10, result:  "20.10"},
    {num: 30.1234, result:  "30.1234"},
    {num: 40.123456, result:  "40.1235"},
    {num: 50.1200, result:  "50.12"},
    {num: 60.123, result:  "60.123"}
].forEach(test);

Comments