Return entire part in Javascript

Asked

Viewed 1,715 times

-1

What’s the difference of 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));

  • An answer that was deleted contained an interesting link, I will leave here: https://jsperf.com/test-parseint-and-math-floor

  • Interesting quote, you’re comparing a truck to a car. It’s not for the same thing.

  • But it shows that, in addition to Usuability, the two commands have difference in performance

  • 1

    Yes, there is a difference in performance, if you add 1 in an integer and have a fractal calculation solved, there is also a difference in performance, and there is no relationship between them, the information has no meaning.

2 answers

5

The parseInt() it shouldn’t be used with number, it even works, but it doesn’t make sense, it analyzes a string and returns an integer if possible from the analyzed text. It’s not a way to take the decimal part, it’s just a side effect.

The Math.floor() makes a rounding, or is close to the highest integer, so -3.7 would give -4 and not -3 as you might expect. By default rounds to zero decimal places, but you can use the amount you want. I believe that it is a little slower if you only want the whole part and should only be used with a number of houses greater than 0 or if it is a variable. The Math.ceil() does the same but approaches the lowest number. And still the Math.round() approaches according to the value, goes on the nearest number.

The Math.trunc() simply despises the decimal part. If this is what you want, and it seems to be, it is the most suitable.

1


The parseint(); will transform a string (string sequence) into an integer that is if you have an "as1" string it converges to 1 or if there is a conversion error it will return an Nan

The Math.Floor() will always round down a floating number (float) 3.966 turns 3, but unlike parseint it does not convert string into numbers and will cause application error

The Math.Trunc() I 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]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.