Thursday, June 29, 2017

JavaScript Recipe: Round to a number of decimal places stripping trailing zeros

JS uses binary floating point to handle decimal based operations.
JavaScript calculations with floating point causes the Nonsense cases especially during the result comparisons & displaying.
If the variable was created as a Number, not a String, extra trailing zeros would be dropped automatically.

Round to a maximum number of fraction digits

  • toFixed() - round to the last indicated decimal position.

      var n = 50.777;
      n.toFixed(2);          // "50.78"
    

    Watchout: it returns a String!

    Note: it will return extra trailing digits if the number of places is higher, than actual number of fraction digits:

      95.56789.toFixed(5);   // "50.77700"
    

Remove insignificant trailing zeros from number

If you define number with trailing zeros they're dropped:

var n = 50.77700;
// n = 50.777
  • parseFloat() - converts a strings with decimals into numbers; so it will automatically drop any trailing 0's

      var n = "50.77700";
      parseFloat(n);        // 50.777
    

Round to a number of places and drop trailing zeros

JavaScript
function roundDecimal(value, maxFractionDigits) {
  if (!isItDamnNumber(value) || !isItDamnNumber(maxFractionDigits)) {
    throw "Number is expected as an argument!"
  }
  return parseFloat(value.toFixed(maxFractionDigits))
}

function isItDamnNumber(data) {
    return typeof data === "number" && !isNaN(data);
}

Here how it looks in TypeScript:

TypeScript
const roundDecimal = (val: number, maxFractionDigits: number): string => {
  return parseFloat(val.toFixed(maxFractionDigits)).toString();
};

console.log(roundDecimal(50.77, 10));  // '50.77'

see Also


3 comments:

  1. nice information
    Yaaron Studios is one of the rapidly growing editing studios in Hyderabad. We are the best Video Editing services in Hyderabad. We provides best graphic works like logo reveals, corporate presentation Etc. And also we gives the best Outdoor/Indoor shoots and Ad Making services.
    Best video editing services in Hyderabad,ameerpet
    Best Graphic Designing services in Hyderabad,ameerpet­
    Best Ad Making services in Hyderabad,ameerpet­

    ReplyDelete
  2. Hi, Amazing your article you know I'm too lazy to sign up an account just for comment your article. it's really good and helping dude. thanks!
    JavaScript Training Course in Delhi

    ReplyDelete
  3. Good day. I was impressed with your article. Keep it up . You can also visit my site if you have time. Thank you and Bless you always.
    Hire Angular Developer in India

    ReplyDelete