skip to Main Content

They both seem to do the exact same thing. (i.e converting float numbers to integers, and work on strings)

I couldn’t find any difference, I even asked ChatGPT it said Math.trunc can’t work on strings which is wrong! it works on numbers and strings.

2

Answers


  1. Yes, there are differences between parseInt and Math.trunc methods in JavaScript

    parseInt("10");      // Output: 10 
    Math.trunc(10.9);   // Output: 10
    
    Login or Signup to reply.
  2. In general, they do fundamentally different operations that often (but not always) produce the same results. parseInt is designed to parse a string value into a number. One advantage here is handling other bases (allowing you to express hex or binary strings, not just decimals). Because it assumes your input is a string, it will coerce any input you give it into a string before parsing (even if the value is already numeric). This can have some unexpected side-effects (for example, if the string value of some number would display in scientific notation, you will likely get a much larger or smaller value than you expect).

    Math.trunc, on the other hand, expects a numeric. It appears to coerce the value you give it (including a string) into a number, then drops everything after the decimal. While in many cases they will produce the same results, there are many where they won’t. It is more likely to give you NaN (such as when you have odd/unexpected additional characters in the string you pass it), but this may also be a good thing from a user-input validation standpoint.

    The correct function will depend on your use case. In general, if you have a string and you know it’s base, use parseInt. If you just want the integer portion of a decimal number, but that number may be in scientific notation (or you want to know of the string has extraneous characters and fail parsing), Math.trunc may be more appropriate.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search