I\'m passing as parameter an id to a javascript function, because it comes from UI, it\'s left zero padded. but it seems to have (maybe) \"strange\" behaviour?
If number came from server as zero padded string then use +"0000022115"
console.log(+"0000022115")
if (021 < 019) console.log('Paradox');
JS treat zero padded numbers like octal only if they are valid octal - if not then it treat it as decimal. To not allow paradox 'use strict'
mode
'use strict'
if (021 < 019) console.log('Paradox');
If you start it with a 0, it's interpreted as an Octal number.
See http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference#quickIDX2
Note the article's warning here:
You should never precede a number with a zero unless you are specifically looking for an octal conversion!
Consider looking here for ideas on removing the leadings 0s: Truncate leading zeros of a string in Javascript
Try
/^[0]*([1-9]\d)/.exec(numberFromUI)[0]
That should give you just the numbers stripping the zeros (if you have to support decimals, you'll need to edit to account for the '.', and of course ',' is fun too... and I really hope you don't have to handle all the crazy different ways Europeans write numbers! )
Leading 0
s indicate that the number is octal.
parseInt
parses a string containing a number.
parseInt(0000022115, 10)
passes a numeric literal. The literal is parsed in octal by the JS interpreter, so you're passing a raw numeric value to parseInt
.
Unless you can intercept a string version of this number, you're out of luck.
That being said, if you can get a string version of your octal (calling toString()
won't help), this will work:
parseInt(variable_string.replace(/^0+/, ''), 10);
If you receive your parameters as string objects, it should work to use
parseInt(string, 10)
to interpret strings as decimal, even if they are beginning with 0.
In your test, you pass the parseInt method a number, not a string, maybe that's why it doesn't return the expected result.
Try
parseInt('0000022115', 10)
instead of
parseInt(0000022115, 10)
that does return 221115 for me.