FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Maths/IntToBase.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Maths
/
IntToBase.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
40 lines (39 loc) · 1.3 KB
Breadcrumbs
JavaScript
/
Maths
/
IntToBase.js
Copy path
File metadata and controls
40 lines (39 loc) · 1.3 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
39
40
/**
*
@function
intToBase
*
@description
Convert a number from decimal system to another (till decimal)
*
@param
{
Number
} number Number to be converted
*
@param
{
Number
} base Base of new number system
*
@returns
{
String
} Converted Number
*
@see
[HornerMethod](https://en.wikipedia.org/wiki/Horner%27s_method)
*
@example
* const num1 = 125 // Needs to be converted to the binary number system
* gornerScheme(num, 2); // ===> 1111101
*
@example
* const num2 = 125 // Needs to be converted to the octal number system
* gornerScheme(num, 8); // ===> 175
*/
const
intToBase
=
(
number
,
base
)
=>
{
if
(
typeof
number
!==
'number'
||
typeof
base
!==
'number'
)
{
throw
new
Error
(
'Input data must be numbers'
)
}
// Zero in any number system is zero
if
(
number
===
0
)
{
return
'0'
}
let
absoluteValue
=
Math
.
abs
(
number
)
let
convertedNumber
=
''
while
(
absoluteValue
>
0
)
{
// Every iteration last digit is taken away
// and added to the previous one
const
lastDigit
=
absoluteValue
%
base
convertedNumber
=
lastDigit
+
convertedNumber
absoluteValue
=
Math
.
trunc
(
absoluteValue
/
base
)
}
// Result is whether negative or positive,
// depending on the original value
if
(
number
<
0
)
{
convertedNumber
=
'-'
+
convertedNumber
}
return
convertedNumber
}
export
{
intToBase
}
Back
|
FazBrowse Home
|
New Git URL