Return whole part in JavaScript

0

What's the difference between these methods in JavaScript?

console.log(parseInt(3.3));
console.log(parseInt(3.7));

console.log(Math.floor(3.3));
console.log(Math.floor(3.7));

console.log(Math.trunc(3.3));
console.log(Math.trunc(3.7));
    
asked by anonymous 25.04.2018 / 20:11

2 answers

1

parseInt (); will transform a string (character sequence) in an integer that is, if you have a string "as1" it converts to 1 or if some conversion error occurs, it will return a NaN

The Math.Floor () will always round a floating number (float) down or 3.966 turns 3, but different from parseInt it does not convert string to numbers and will cause application error

The Math.Trunc () return the number after the comma

They are very similar functions, but can not always be replaced by the other

var v = 3.14;
[Math.trunc(v), Math.floor(v), Math.ceil(v), Math.round(v)]
// print dos resutados

      t   f   c   r
 3.87 : [ 3,  3,  4,  4]
 3.14 : [ 3,  3,  4,  3]
-3.14 : [-3, -4, -3, -3]
-3.87 : [-3, -4, -3, -4]
    
25.04.2018 / 20:21
5

parseInt() should not be used with number, until it works, but does not make sense, it parses a string and returns an integer if it is possible from the parsed text. It's not a way to get the decimal part out, that's just a side effect.

Math.floor() rounds, or is about the highest integer, then -3.7 would give -4 and not -3 as you might expect. By default it rounds to zero decimal places, but you can use the amount you want. I believe it is a bit slower if it just wants the whole part and should only be used with a number of houses greater than 0 or if it is a variable. Math.ceil() does the same but approaches the number lower. And even the Math.round() approaches according to the value, it goes in the nearest number.

Math.trunc() purely and simply disregards decimal part. If this is what you want, and it seems to be, it is the most appropriate.

    
25.04.2018 / 20:47