DEV Community

Discussion on: You should stop using `parseInt()`

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

there are of course use cases where it’s beneficial to use it, for example if you want to extrapolate an integer out of a floating number, which is a good 50% faster than Math.round().

Two things here -

  1. parseInt doesn't do any rounding, only truncation. The equivalent Math function would be Math.trunc:

    Math.round('0.999') // 1
    Math.trunc('0.999') // 0
    parseInt('0.999')   // 0
    
    Math.round('-0.999') // -1
    Math.trunc('-0.999') // -0
    parseInt('-0.999')   // -0
    
  2. Running benchmarks in Chrome, the performance benefit of parseInt over Math.round is reversed if you explicitly convert to a number first:

    const bench = (desc, cb) => {
        const start = new Date()
    
        for (let i = 0; i < 1e7; ++i) {
            cb()
        }
    
        const end = new Date()
    
        console.log(desc, `${end - start} ms`)
    }
    
    bench('parseInt',       () => parseInt('3.2', 10))       // 374 ms
    bench('round coerced',  () => Math.round('3.2'))         // 738 ms
    bench('round explicit', () => Math.round(Number('3.2'))) //  70 ms
    bench('trunc coerced',  () => Math.trunc('3.2'))         // 671 ms
    bench('trunc explicit', () => Math.trunc(Number('3.2'))) //  62 ms
    
Collapse
 
darkmavis1980 profile image
Alessio Michelini

Good to know, thanks!

Collapse
 
ilumin profile image
Teerasak Vichadee

Kudos!