Javascript - number conversion
Javascript have three functions for converting nonnumberic value to numbers:
- Number();
- parseInt();
- parseFloat();
Empty string:
Number("") = 0
parseInt("") = NaN
parseFloat("") = NaN
Parsing with first lending a letter:
Number("a1") = NaN
parseInt("a1") = NaN
parseFloat("a1") = NaN
Parsing with first lending 1 number:
Number("1a") = NaN
parseInt("1a") = 1
parseFloat("1a") = 1
Parsing hexadecimal (10):
Number("0xA") = 10
parseInt("0xA") = 10
parseFloat("0xA") = 0
Lending zeros are ignored:
parseFloat("001") = 1
parseInt("001") = 1
Number("001") = 1
Parsing floating numbers with lending zeros:
parseFloat("00.1") = 0.1
parseInt("00.1") = 0
Number("00.1") = 0.1
Parsing floating numbers without lending zeros:
parseFloat("0.1") = 0.1
parseInt("0.1") = 0
Number("0.1") = 0.1
Parsing booleans:
Number(true) = 1
Number(false) = 0
parseFloat(true) = NaN
parseFloat(false) = NaN
parseInt(true) = NaN
parseInt(false) = NaN
Parsing null:
Number(null) = 0
parseFloat(null) = NaN
parseInt(null) = NaN
Parsing undefined:
Number(undefined) = NaN
parseFloat(undefined) = NaN
parseInt(undefined) = NaN
Parsing NaN:
Number(NaN) = NaN
parseFloat(NaN) = NaN
parseInt(NaN) = NaN
Parsing positive negative floating numbers:
parseFloat("+1.1") = 1.1
parseFloat("-1.1") = -1.1
parseInt("+1.1") = 1
parseInt("-1.1") = -1
Number("+1.1") = 1.1
Number("-1.1") = -1.1
Wightespace is ignored:
parseInt(" +1") = 1
parseInt(" -1") = -1
parseFloat(" +1") = 1
parseFloat(" -1") = -1
Number(" +1") = 1
Number(" -1") = -1
parseInt suport radix or base:
parseInt("10",2) = 2 //binary
parseInt("10",8) = 8 //octal
parseInt("10",10) = 10 //decimal
parseInt("10",16) = 16 //hexadecimal
All test cases are hire:
http://jsfiddle.net/zbL7H/3/
Written by Igor Ivanovic
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside