David Rodrigues
David Rodrigues

Reputation: 12532

Javascript: parsing negative Number(hexadecimal | binary)

It works with a lot number types, but not with negatives hexadecimal or binary. Too, Number(octal) doesn't parse an octal number.

Number("15")    ===   15;  // OK
Number("-15")   ===  -15;  // OK
Number("0x10")  ===   16;  // OK
Number("0b10")  ===    2;  // OK
Number("-0x10") ===  NaN;  // FAIL (expect  -16)
Number("-0b10") ===  NaN;  // FAIL (expect   -2)
Number("0777")  ===  777;  // FAIL (expect  511)
Number("-0777") === -777;  // FAIL (expect -511)

Question: how I can parse all valid Javascript numbers correctly?

Edit A

parseInt() don't help me because I need check by each possibility (if start with 0x I use 16, for instance).

Edit B

If I write on Chrome console 0777 it turns to 511, and too allow negative values. Even works if I write directly into javascript code. So I expect basically a parser that works like javascript parser. But I think that the negative hexadecimal, for instance, on really is 0 - Number(hex) in the parser, and not literraly Number(-hex). But octal values make not sense.

Upvotes: 5

Views: 3403

Answers (4)

Matt Burland
Matt Burland

Reputation: 45135

This gets a little ugly, but you could inspect the values to determine the right radix for parseInt. In particular, the b for binary doesn't seem to be support by my browser (Chrome) at all, so unlike the OP, Number("0b10") gives me NaN. So you need to remove the b for it to work at all.

var numbers = [
  "15", "-15", "0x10", "0b10", "-0x10", "-0b10", "0777", "-0777"
];

function parser(val) {
  if (val.indexOf("x") > 0) {
    // if we see an x we assume it's hex
    return parseInt(val, 16);
  } else if (val.indexOf("b") > 0) {
    // if we see a b we assume it's binary
    return parseInt(val.replace("b",""),2);
  } else if (val[0] === "0") {
    // if it has a leading 0, assume it's octal
    return parseInt(val, 8);
  }
  // anything else, we assume is decimal
  return parseInt(val, 10);
}

for (var i = 0; i < numbers.length; i++) {
  console.log(parser(numbers[i]));
}

Note this obviously isn't foolproof (for example, I'm checking for x but not X), but you can make it more robust if you need to.

Upvotes: 0

user2191247
user2191247

Reputation:

It's not parsing octal and the other examples because they're not valid Javascript numbers, at least within the constraints of Number. So the technically correct answer is: use Number!

If you want to parse other formats, then you can use parseInt, but you will have to provide the base.

Upvotes: 0

KJ Price
KJ Price

Reputation: 5964

You could write a function to handle the negative value.

function parseNumber (num) {
   var neg = num.search('-') > -1;
   var num = Number(num.replace('-', ''));
   return num * (neg ? -1 : 1);
}

Upvotes: 2

Dzmtrs
Dzmtrs

Reputation: 446

Try this:

parseInt(string, base):

parseInt("-0777", 8) 
parseInt("-0x10", 16) 

Upvotes: 3

Related Questions