Couple of weeks ago I was writing JavaScript, while unit testing I came across very strange bug that I could not figure it out. The number I was trying to parse was "08", when I used parseInt without radix I got the result "0"
parseInt("08") --> returned "0"
parseInt("0222") --> returned "146"
parseInt("08", 10) --> returns "8"
parseInt("0222", 10) --> returned "222"
The reason for this strange phenomenon lies in radix. Syntax for parseInt is parseInt(string, radix), where string part is required and radix is optional. When you don't provide radix, JavaScript tried to determine radix from given sting.
if your string begins with "0", it assumes radix is 8(octal)
if your string beings with "0x", it assumes radix is 16(Hex) otherwise it will assume that radix is 10 (decimal)
If you don't specify radix and if you are certain that string that will be parsed using parseInt will never have "0" as leading character then I would say skipping radix parameter is fine.
No comments:
Post a Comment