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?
You can use Math.round() for rounding numbers to the nearest integer.
Also, you can use parseInt() and parseFloat() to cast a variable to a certain type, in this case integer and floating point.
Math.floor(19.5) = 19 should also work.
You hav to convert your input into a number and then round them:
Or as a one liner:
Testing with different values:
A very good approximation for rounding:
Only in some cases when the length of the decimal part of the number is very long will it be incorrect.
Here is a way to be able to use
Math.round()
with a second argument (number of decimals for rounding):According to the ECMAScript specification, numbers in JavaScript are represented only by the double-precision 64-bit format IEEE 754. Hence there is not really an integer type in JavaScript.
Regarding the rounding of these numbers, there are a number of ways you can achieve this. The Math object gives us three rounding methods wich we can use:
The Math.round() is most commonly used, it returns the value rounded to the nearest integer. Then there is the Math.floor() wich returns the largest integer less than or equal to a number. Lastly we have the Math.ceil() function that returns the smallest integer greater than or equal to a number.
There is also the toFixed() that returns a string representing the number using fixed-point notation.
Ps.: There is no 2nd argument in the Math.round() method. The toFixed() is not IE specific, its within the ECMAScript specification aswell