Reputation: 120
Is there any trick to convert string to integer in javascript without using any function and methods?
var s = "5"
console.log(typeof(s)) // out put is string
console.log(typeof(parseInt(s))) // i want out put which is number with out using parseInt() or other functions for optimizing code.
Any help would be appreciated. Thanks in advance.
Upvotes: 5
Views: 4619
Reputation: 2068
Basically if you are searching "whole logic" to convert string to int then you have to find ASCII code for each alphabet in string and then convert it to integer and make sum of all 48 to 57 are ASCII codes are for number 0 to 1. Below is example code
let parseINT = (b) => b.split("").map((e,i) => {
let value = e.charCodeAt(0) - 48;
return value * [...Array(((i - b.length) * -1)).keys()].reduce((a, b) => a > 0 ? (a * 10) : 1, 0);
}).reduce((a, b) => a + b, 0)
or short form will be like
let parseINT = (b) => b.split("").map((e,i) => ((e.charCodeAt(0) <= 57 ? e.charCodeAt(0) : 48) - 48) * [...Array(((i - b.length) * -1)).keys()].reduce((a, b) => a > 0 ? (a * 10) : 1, 0)).reduce((a, b) => a + b, 0);
Upvotes: 0
Reputation: 958
here is a most effective way to convert string into int without using any built in function have a look at code. Thank you:)
var s = "5"
var i = s - 0
console.log(typeof(i)) // you will get a number without using any built in function... because (-) will cast string in to number
Upvotes: 5
Reputation: 68933
You can cast the string to number using unary plus (+
). This will do nothing much beside some code optimization.
var s = "5"
s = +s;
console.log(typeof(s), s);
var s = "5.5"
s = +s;
console.log(typeof(s), s);
Upvotes: 6
Reputation: 24955
You can try using bit-wise operator s|0
. This will convert value to integer. However, this will also convert floating values to integer.
var s = "5"
var y = s|0;
console.log(typeof(y), s, y);
var s = "5.5"
var y = s|0;
console.log(typeof(y), s, y);
Upvotes: 3