program for conversion to another base works in c++ but not in JavaScript

I made a c++ program which converts natural numbers to a base from 0 to 16. It works. The whole code is here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>

using namespace std;

string to_base (int number,int base)
{
    string bases = "0123456789ABCDEF";
    string result = " ";

    do{
        result = bases[ number%base ]+result;
        number = number/base;
    }while(number>0);

    return result;
}

int main(){
    int a,b,ok;
    do{
        do{
 cout<<"Enter a natural number ";
  cin>>a;
    }while(a<=0);
    do{
        cout<<"enter a base to which convert the given number(2-16): ";
        cin>>b;
    }while ((b<2)||(b>16));

cout<<"number "<<a<<" in base "<<b<<" is: "<<to_base(a,b)<<endl;

    cout<<"Do you want to continue(1) or finish(0)?"<<endl;
    cin>>ok;
}while(ok==1);
return 0;
}



But unfourtunately my JavaScript code for the same program gives me a result of something like: 001010101010111011
Why is that?
Any help will be gladly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  <script>
function to_base(number, base) {
	bases = "01234566789ABCDEF";
	result = "";
	do {
		result = bases.charAt(number % base) +result ;
		number = number/base;
	} while (number > 0);
	return result;
}
do{
	do{
var a = Number(prompt("Enter a natural number: "," "));
}while(a<=0);
	do{
var b = Number(prompt("Enter a base to which convert(2-16): "," "));
}while((b<2)||(b>16));
var texxt = "number " + a +" base " + b + " is " +to_base(a,b);


window.alert(texxt);
var ok = Number(prompt("Do you want to continue(1) or finish  (0)?" , " "));
}while(ok==1);
   


</script>
In JavaScript everything is a double so lines 7 and 8 go on and on getting ever closer to zero.
For example, for to_base(153, 10) you get:
1
2
3
4
5
6
7
8
9
15.3
1.53
0.153
0.0153
0.00153
0.000153
0.0000153
0.00000153
/*so on*/

That's why you get a lot of zeroes, because none of these decimals are exactly zero.

To fix this you need to encapsulate number/base in Math.floor()
1
2
3
4
5
6
7
8
9
function to_base(number, base) {
	bases = "01234566789ABCDEF";
	result = "";
	do {
		result = bases.charAt(number % base) +result ;
		number = Math.floor(number/base);
	} while (number > 0);
	return result;
}


I admit my code in my past post was not quite correct but you need to bear in mind this is a C++ forum, not for JavaScript.
Topic archived. No new replies allowed.