1

I have a program that must take in input any number, and it can begin with 0, for example:

const nb1=043
const nb2=134

function multiply(nb1,nb2){

    const result=nb1*nb2;
    console.log(" nb1 and nb2 "+result, nb1, nb2);

}

The problem in the output 043 was raplced by 35

nb1 and nb2 4690 35 134

Chedi Bechikh
  • 183
  • 3
  • 13
  • 1
    *"Why number is changing when it begin with zero?"* Because you're using loose mode and in loose mode in most environments a leading `0` indicates a legacy octal literal. To fix it: 1. Use [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) (`"use strict";` at the top, and/or use modules which are strict by default), and 2. Don't start a decimal literal with `0`. :-) – T.J. Crowder May 13 '20 at 14:06
  • Helpful: [Javascript, why treated as octal](https://stackoverflow.com/questions/9071696/javascript-why-treated-as-octal) – Ed Lucas May 13 '20 at 14:08
  • the program must be able to take any input, suppose the user give you this kind of input, also i didn't post all the code, its used in a recursive function for the karatsuba multiplication so if it is 46 it must be padded with 046 if we multiply 46 by 134 – Chedi Bechikh May 13 '20 at 14:09
  • 2
    The `035` interpenetrated by JavaScript as Octal number `043 = (0 × 8²) + (4 × 8¹) + (3 × 8⁰) = 35` – Slava Rozhnev May 13 '20 at 14:11
  • If you are not using any framework\transpiling library then it's best to tell compiler your intentions by either using parseInt or 'use strict'. If you really want to get to the bottom of then watch\read js the good parts by Douglas Crockford. – foo-baar May 13 '20 at 14:13
  • 1
    @ChediBechikh How do you get this input? You only get this output for number literals. If you use `parseInt("043")` it will return `43` just fine. – Ivar May 13 '20 at 14:15
  • @Ivar - Sadly, that didn't used to be true. (But it is now, even in IE11.) – T.J. Crowder May 13 '20 at 14:15
  • @T.J.Crowder: if I change the question it will not stay as duplicate , how to force my code to not change number that start with zero? – Chedi Bechikh May 13 '20 at 14:17
  • 1
    If you're receiving these as numbers from a user, presumably they're using decimal and you're receiving strings. You can use `parseFloat` to reliably parse them as decimal, even with a leading 0 (even on older browsers). – T.J. Crowder May 13 '20 at 14:17
  • 1
    @ChediBechikh - See above. :-) (That question in your comment -- which is different from the one you asked in the question above -- is also well-represented here on SO.) – T.J. Crowder May 13 '20 at 14:18
  • 1
    @Ivar - I bet they're dumping out user input into a JavaScript section of an HTML page, for instance from PHP: `var n = ;` – T.J. Crowder May 13 '20 at 14:20

0 Answers0