0

I'm trying to convert a string to an int. When the string is a number with a leading zero, it seems Google Script gets into trouble. Converting "07" to 7 works fine, converting "08" ends in a NaN.

function test_parse_int() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // parses to 7
  ss.toast( parseInt("07") );
  // parses to NaN ?!?
  ss.toast( parseInt("08") );
}

I tested that against JavaScript and there it works fine.

<script>
// parses to 7
document.writeln(parseInt("07"));
// parses to 8
document.writeln(parseInt("08"));
</script>

This behaviour doesn't make any sense to me, is this a bug? Am i missing something?

2
  • 3
    The keyword is "octal", use the radix argument to parse correctly. Commented Jun 4, 2018 at 5:04
  • "Many implementations have not adopted this behavior as of 2013, and because older browsers must be supported, always specify a radix" Alright, i see. Thanks! Commented Jun 4, 2018 at 5:13

1 Answer 1

1

Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt [Credits to @teemu comment]

If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

So explicityly mention the radix

Something like this :

function test_parse_int() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // parses to 7
  ss.toast( parseInt("07", 10) );
  // parses to NaN ?!?
  ss.toast( parseInt("08", 10) );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.