parseInt() not only parses but also truncates! is it okay?

parseInt() not only parses but also truncates! is it okay?

#JavaScript has two global methods named: parseFloat() and parseInt(). On the other hand there is only one data type to represent numbers in JS: "Number".

Technically, parseInt is just the same as parseFloat except that it also truncates the given number in case it includes some decimal part.

The point is that the behavior of parseInt is not actually parsing a string containing int! in fact it is parsing a float and then processing the result. I think there is a bad semantic gap between the meaning of the term used for that method and what it actually does. That may reduce readability of your code and misguide programmers reviewing your code, specially in case they are not completely familiar with JS.

Maybe ECMAScript has better drop those methods and introduce just a single parseNumber() method! and leave rounding to developers themselves!

function parseNumber(str) {
  return parseFloat(str); // may return NaN, which should be handled by the caller!
}


function dropDecimalPart(num) {
  return Math.trunc(num);
	
}

cover photo: by Fatos Bytyqi on Unsplash

#cs_internship #web

要查看或添加评论,请登录

Shahryar Saljoughi的更多文章

  • CSS Note: How to make Child's margin contribute to parent's height!

    CSS Note: How to make Child's margin contribute to parent's height!

    CSS really bothers me, whenever I have to use it, I find out more unwritten untold shitty rules! Here we are gonna…

  • How can telnet client act as Http client?

    How can telnet client act as Http client?

    I was just reading this article and got surprised when it said that you can use telnet to send HTTP requests. But…

  • One Way Data Binding in Pure JS

    One Way Data Binding in Pure JS

    It is a simple task to do but we are too accustomed to having it be handled by frameworks to do it in pure javascript…

    1 条评论
  • Drive C is Full? Handle it Like a .Net Developer!

    Drive C is Full? Handle it Like a .Net Developer!

    drive C is always full and it drives me crazy. Whenever I want to install a utility first I need to free up some space .

  • How does JavaScript Hoisting really work?

    How does JavaScript Hoisting really work?

    w3schools js reference simply states that Hoisting is JavaScript's default behavior of moving declarations to the top…

  • misunderstanding of JS Compilation

    misunderstanding of JS Compilation

    We all had heard that JavasSript is an interpreted language, surprisingly in the second step of #cs_internship#web…

  • A CSS Note On Combination of Float and Overflow

    A CSS Note On Combination of Float and Overflow

    The code snippet below, will generate a navigation bar like the one above. CTYPE html ul { ? list-style-type:…

    2 条评论

社区洞察

其他会员也浏览了