Search code examples
javascriptfloating-pointnumbersrounding

How do I round a number in JavaScript?


While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2

etc.

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though. How would I go about writing a method that takes these sometimes-floats and makes them integers?


Solution

  • You hav to convert your input into a number and then round them:

    function toInteger(number){ 
      return Math.round(  // round to nearest integer
        Number(number)    // type cast your input
      ); 
    };
    

    Or as a one liner:

    function toInt(n){ return Math.round(Number(n)); };
    

    Testing with different values:

    toInteger(2.5);           // 3
    toInteger(1000);          // 1000
    toInteger("12345.12345"); // 12345
    toInteger("2.20011E+17"); // 220011000000000000