DEV Community

Cover image for Vanilla JavaScript String to Number

Vanilla JavaScript String to Number

Chris Bongers on August 04, 2020

Sometimes we want to convert a number to a string; in my latest code piece, there was a limit set on a data attribute. This comes true as a string,...
Collapse
 
rrdlpl profile image
R

+'1'

Collapse
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

Keep in mind that this also works for hexadecimal.

console.log(+"0xF"); // 15
console.log(+"321"); // 321

And so does ~~

console.log(~~"0xF"); // 15
console.log(~~"321"); // 321
Collapse
 
dailydevtips1 profile image
Chris Bongers

I Actually didn't know about the ~~ What is it called?

Thread Thread
 
rrdlpl profile image
R • Edited

it's the NOT bitwise operator. It changes the 1 by 0 and 0 by 1. In that example, he is doing it twice.

~ 5 => ~0101 => 1010
~~5 => ~(~0101) => ~(1010) => 0101 => 5

w3schools.com/js/js_operators.asp

Collapse
 
dailydevtips1 profile image
Chris Bongers

😂👏

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I do realize all methods, but never notice that parseFloat trims, but Number return NaN.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yes, Number is very strict the string can only contain actual numbers!

Collapse
 
craignicol profile image
Craig Nicol (he/him)

Worth knowing that this depends on the user's browser locale. 13,37 is a valid number in French and German, whereas 13.37 is not.

Collapse
 
dailydevtips1 profile image
Chris Bongers

You are right, there is the option to use locales on strings and numbers before. but your right good to keep this in mind!

Collapse
 
g33knoob profile image
G33kNoob • Edited

Keep posting daily tips, i love to read and learning it
I use parsefloat to parsing bitcoin balance from rpc in my current project

Collapse
 
dailydevtips1 profile image
Chris Bongers

Awesome, thanks man! Glad people find them amazing 🤟

Collapse
 
furkankozen profile image
Furkan Közen

~~’1’

Collapse
 
dailydevtips1 profile image
Chris Bongers

I just saw above, actually didn't know that option 🤯