Number tips
0 before a number changes it to base 8
If you accidentally type a 0 in front of a number, the numbers base will change to 8. Let us look at an example.
var number = 011;
alert(number);
Alert wil show the number 9. This is because 011 in base 8 is (0 * 0) + (1 * 8) + (1) = 9.
Add true to a number
True and false are Boolean variables. However true has also the value of 1.
var a = 5;
var b = true;
alert(a + b) will give 6.
We can use this for example to test how often the outcome of a function us true. Here is an example where we count how many times the letter o occurs in a text. The value of counto is increased every time when (a.charAt(i)=="o") is true.
var text = "The author of this book is Luc Volders"
var counto=0;
var i;
for (i=0; i<text.length; i++)
{
counto = counto + (text.charAt(i)=="o");
}
alert(counto);
Click hConvert a binary to an integer
Use the next snippet to convert a binary number in a string to an integer.
test = "11111111"
alert(parseInt(test, 2));ere to edit.
Use the next snippet to convert a binary number in a string to an integer.
test = "11111111"
alert(parseInt(test, 2));ere to edit.
Convert an integer to a float
If you need to convert an integer to a floating poit value you can use the next commands:
var int = 25;
var float = parseFloat(int).toFixed(2);
console.log(float);
The number in toFixed(2) decides how many zeroes will be added behind the decimal point.
If you need to convert an integer to a floating poit value you can use the next commands:
var int = 25;
var float = parseFloat(int).toFixed(2);
console.log(float);
The number in toFixed(2) decides how many zeroes will be added behind the decimal point.
Convert a number to binary
Here is a quick way to convert a number to its binary value. The outcome is a string.
var a = (14 >>> 0).toString(2)
alert(a + " " + typeof a);
Convert a number to an integer
Using Math.floor() , Math.ceil() or Math.round() we can convert a floating point number to an integer. However the outcome is dependend wether you are working with positive or negative numbers. If you just want to truncate the number you can use the following code.
alert(23.9 | 0);
alert.log(-23.9 | 0);
The alerts will show 23 and then -23
The advantage over Math.trunc is that if you use this code on a string the outcome will be 0.
Convert a number to a string
Here is an easy way to convert a number (integer or float) to a string:
let value = 33.15 + "";
alert(value);
alert(typeof value);
By adding an empty string to a number, the number will be converted to a string.
Convert a number to a string 2
Using string literals we can easily add variables to a string like this:
amount = 10;
alert(`Hi the amount to pay is ${amount}`);
We can also use string literals to convert numbers to strings in this way:
stringnumber = `${amount}`;
alert(typeof stringnumber);
Count the amount of digits in a number
We humans can see in a wink that 9000 is a number in the thousands because it has 4 digits. If you want to check that in Javascript use the next code.
number = 2353454;
a = number.toString();
alert(a.length)
This way you can determine if a number is in tens, hundreds or thousands etc.
Create even numbers
To create even numbers you start with 0 or 2 (or any other even number) and keep adding 2.
var even = 2;
for (i = even; i<11; i=i+2)
{
console.log (i)
}
To create even numbers you start with 0 or 2 (or any other even number) and keep adding 2.
var even = 2;
for (i = even; i<11; i=i+2)
{
console.log (i)
}
Create odd numbers
To create odd numbers you start with 1 (or any other odd number) and keep adding 2.
var even = 1;
for (i = even; i<11; i=i+2)
{
console.log (i)
}
To create odd numbers you start with 1 (or any other odd number) and keep adding 2.
var even = 1;
for (i = even; i<11; i=i+2)
{
console.log (i)
}
Get a figure out of a string
If you need to get a number out of a string that contains text and the number you can use regex to achieve this.
let string = "€25.00 Euro";
let number = string.replace(/[^0-9.]/g, "");
alert(number);
The alert will show 25.00
Get all primenumbers up until a certain value
Prime numbers are often used in math calculations and in cryptography. The next snippet shows an easy way to get all prime numbers up until a certain value which is 100 in this example.
for (let prime = 1; prime <= 100; prime++)
{
let a = false;
for (let i = 2; i <= prime; i++)
{
if (prime%i===0 && i!==prime)
{
a = true;
}
}
if (a === false)
{
document.write(prime +"<br>");
}
}
The test if a number is a primenumber is done by: if (prime%i===0 && i!==prime)
A number is only a priome number when it is divisbkle by 1 and itself. A number divided by another number has a rest of 0 (modulus 0) then it is only divisble by itself.
How many figures after the decimal point
If you want to know how many figures there are after then decimal point
you can use the following code.
var amount = 3.142857142857;
var count;
var teststring = String(amount);
if (teststring.includes('.'))
{
count = teststring.split('.')[1].length;
}
else
{
count = 0;
}
alert(count)
The alert will show that bthere are 12 figures behind the decimal point.
If you entered an integer then the variable count will have 0 as value.
Random number from 1 to N
To get a random number from 1 to N use the next snippet.
var number = Math.floor(Math.random() * N + 1);
You need to add 1 to Math.floor(Math.random() * N) because the outcome of this formula might be 0.
Random number from X to Z
This tip looks the same as the tip where we get a random number from 1 to N. Here we generate a random number from a starting to an ending point.
minimal = 5;
maximum = 20;
randomnumber = Math.random() * (maximum - minimal+1) + minimal;
Using the tip "Convert a number to an integer" to convert randomnumber into an integer.
Random number within a range
Using Math.random() you can generate a random number between 0 and 1. To generate a random number between a minimum and maximum you will need to multiply the Math.random() value with the difference between the minimum value and maximum value +1. The +1 is needed as otherwise the maximum number is not included. Here is an example snippet that bshows how to do this.
var min = 5;
var max = 15;
function randomminmax(min, max)
{
// +1 to include the max range
const random = Math.random() * (max - min + 1);
const whole = Math.floor(random) + min;
return whole;
}
document.write(randomminmax(min,max));
Random number with 5 digits
To generate a random number with 5 digits you can use the following code:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
To generate a random number with 5 digits you can use the following code:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Remove the last x figures of a number
By making clever use of the || function we can remove any number of last figures from a number. Here is an example that demonstrates this.
alert(1234 / 10 | 0) // the result is 123
alert(1234 / 100 | 0) // the result is 12
alert(1234 / 1000 | 0) // the result = 1
Remove the leading 0
For removing a leading 0 in a number inside a string use the next snippet.
var number = String(parseInt("0250 jaar"));
alert (number);
The command parseInt() removes the first zero's and the rest of the text. The string number will afterwards only contain "250"
Reverse a number
If you need to reverse a number you can use the following code.
number = number +"";
number = number.split("");
number = number.reverse();
number = number.join("");
number = +number;
alert(typeof number);
You can combine these command to one line:
number=+((number+"").split("").reverse().join(""))
Round a number so it is divisible by x
The next snippet shows how to round a number up so it can be divided by another number and the outcome is an integer.
return Math.ceil(x/y)*y;
Here X is the number that needs to get divided and y is the divider.
As an example gives Math.ceil(1021/3)*3 the number 1023 as outcome. This is because 341 x 3 = 1023.
Using Math.floor(x/y)*y rounds the number down. In our example the outcome therefoer will be 1020.ere to edit.
The next snippet shows how to round a number up so it can be divided by another number and the outcome is an integer.
return Math.ceil(x/y)*y;
Here X is the number that needs to get divided and y is the divider.
As an example gives Math.ceil(1021/3)*3 the number 1023 as outcome. This is because 341 x 3 = 1023.
Using Math.floor(x/y)*y rounds the number down. In our example the outcome therefoer will be 1020.ere to edit.
Round a number to 0.05
The following snippet shows how to round a figure to 5 cents.
alert (Math.round(amount * 20) / 20);
If amount has the value of 6.82 alert will show 6.8. At 6.84 alert will show 6.85
The following snippet shows how to round a figure to 5 cents.
alert (Math.round(amount * 20) / 20);
If amount has the value of 6.82 alert will show 6.8. At 6.84 alert will show 6.85
Round a number to 0.10
If you need to round amounts to 10 cents you can do that easily with this snippet.
alert (Math.round(amount * 10) / 10);
If amount has the value of 6.87 alert will show 6.9.
If you need to round amounts to 10 cents you can do that easily with this snippet.
alert (Math.round(amount * 10) / 10);
If amount has the value of 6.87 alert will show 6.9.
Round a number to 0.20
Rounding a number to 20 cents is easy with the following snippet.
alert (Math.round(amount * 5) / 5);
If amount is 6.3 the alert will show 6.4
Rounding a number to 20 cents is easy with the following snippet.
alert (Math.round(amount * 5) / 5);
If amount is 6.3 the alert will show 6.4
Round a number to 0.25
Rounding a number to .25 is easy with the following snippet.
alert (Math.round(amount * 4) / 4);
If amount has the value of 6.3 then the alert will show 6.25
Rounding a number to .25 is easy with the following snippet.
alert (Math.round(amount * 4) / 4);
If amount has the value of 6.3 then the alert will show 6.25
Round a number to 0.50
Rounding amounts to 50 cents can be done with the following snippet:
alert (Math.round(amount * 2) / 2);
If amount has the value 6.74 alert will show 6.5. At 6.75 alert will show 7.
Rounding amounts to 50 cents can be done with the following snippet:
alert (Math.round(amount * 2) / 2);
If amount has the value 6.74 alert will show 6.5. At 6.75 alert will show 7.
Rounding to a fixed number decimals
Numbers are often floating points and that means that they have a lot of decimal places. We can easily round numbers to a fixed amount of decimal places.
var testnum =6.58436;
testnum = testnum.toFixed(4);
The variable testnum will now be 6.5844. toFixed(4) rounds it to 4 decimal places.
You can easily make a function with this that accepts a number and the amount of decimals as parameters:
function round(number,decimals)
{
number = number.toFixed(decimals);
alert(number);
}
round(6.584683,1);
Numbers are often floating points and that means that they have a lot of decimal places. We can easily round numbers to a fixed amount of decimal places.
var testnum =6.58436;
testnum = testnum.toFixed(4);
The variable testnum will now be 6.5844. toFixed(4) rounds it to 4 decimal places.
You can easily make a function with this that accepts a number and the amount of decimals as parameters:
function round(number,decimals)
{
number = number.toFixed(decimals);
alert(number);
}
round(6.584683,1);
Rounding with toFixed changes a number into a string
As discussed in the previous tip we can round a number to a fixed amount of decimals with the following line:
number = number.toFixed(2);
Be aware thta the command toFixed() changes the number into a string.
For example:
alert(typeof(6.35468.toFixed(2)) + " " + 6.35468.toFixed(2))
var testnum = 6.58436;
testnum = testnum.toFixed(2);
alert(typeof(testnum));
The alert box will display: string
As discussed in the previous tip we can round a number to a fixed amount of decimals with the following line:
number = number.toFixed(2);
Be aware thta the command toFixed() changes the number into a string.
For example:
alert(typeof(6.35468.toFixed(2)) + " " + 6.35468.toFixed(2))
var testnum = 6.58436;
testnum = testnum.toFixed(2);
alert(typeof(testnum));
The alert box will display: string
Split a number in part before and after comma
Splitting a number in the part before and after the comma is easy.
var number = 3.142857142857;
var teststring = String(number);
var beforecomma = teststring.split('.')[0];
var aftercomma = teststring.split('.')[1];
Splitting a number in the part before and after the comma is easy.
var number = 3.142857142857;
var teststring = String(number);
var beforecomma = teststring.split('.')[0];
var aftercomma = teststring.split('.')[1];
Split a number in its figures
If you need to split a number in its figures it is best to first convert it into a string and then use split to put the figures in array elements. Here is an example.
var number = 123;
var string = number.toString();
var figures = string.split("");
alert (figures)
This can be combined ito one statement:
figures = number.toString().split("");
If you need to split a number in its figures it is best to first convert it into a string and then use split to put the figures in array elements. Here is an example.
var number = 123;
var string = number.toString();
var figures = string.split("");
alert (figures)
This can be combined ito one statement:
figures = number.toString().split("");
Split a number in thousands, hundreds etc.
If there is a number that we need to split in thousands, hundreds, tens etc we can do that with the lowwing code:
var amount = 518234;
helperarray = (amount+"").split("");
amountlength = helperarray.length;
units =[];
for (i=0; i<amountlength; i++)
{
units.push(helperarray[i]*Math.pow(10,amountlength-(i+1)));
}
document.write(units);
As the amount is 518234 the alert will show 500000,10000,8000,200,30,4
If there is a number that we need to split in thousands, hundreds, tens etc we can do that with the lowwing code:
var amount = 518234;
helperarray = (amount+"").split("");
amountlength = helperarray.length;
units =[];
for (i=0; i<amountlength; i++)
{
units.push(helperarray[i]*Math.pow(10,amountlength-(i+1)));
}
document.write(units);
As the amount is 518234 the alert will show 500000,10000,8000,200,30,4
Test if a number is an integer
Here is a quick way to test wether a number is an integer.
alert (23.5 % 1 === 0);
The alert will give "false" as the figure divided by 1 has a remainder of 0.5 which is not eqal to zero.
Here is a quick way to test wether a number is an integer.
alert (23.5 % 1 === 0);
The alert will give "false" as the figure divided by 1 has a remainder of 0.5 which is not eqal to zero.
Test wether a number is an integer 2
For testing wether a number is an integer you can use the next code.
var testnumber = "10.5";
if (testnumber === parseInt(testnumber, 10))
alert("Integer!")
else
alert("Not an integer!")
Another method is by using Math.floor:
if (testnumber == Math.floor(testnumber))
Both methods work with numbers and strings that contain a number.
However if the string for example "10C" is then Math.floor() gives Nan and parseInt() gives "Not an integer"
For testing wether a number is an integer you can use the next code.
var testnumber = "10.5";
if (testnumber === parseInt(testnumber, 10))
alert("Integer!")
else
alert("Not an integer!")
Another method is by using Math.floor:
if (testnumber == Math.floor(testnumber))
Both methods work with numbers and strings that contain a number.
However if the string for example "10C" is then Math.floor() gives Nan and parseInt() gives "Not an integer"
Test if a number is an integer 3
You can test if a number is an integer with regex. Here is an example.
var number = 12345
var isnumber = /^\d+$/.test(number);
if (isnumber) {
alert("The number is an integer")
}
You can test if a number is an integer with regex. Here is an example.
var number = 12345
var isnumber = /^\d+$/.test(number);
if (isnumber) {
alert("The number is an integer")
}
Test if a number is positive or negative
A quick way to determine if a number is positive or negative is using Math.sign(number) Math.sign() returns 1 for a positive number and -1 for a negative number.
Here are some examples.
alert(Math.sign(5));
alert(Math.sign(-5));
alert(Math.sign(0));
A quick way to determine if a number is positive or negative is using Math.sign(number) Math.sign() returns 1 for a positive number and -1 for a negative number.
Here are some examples.
alert(Math.sign(5));
alert(Math.sign(-5));
alert(Math.sign(0));
Test wether the input is a number
During a calculation an error wil be generated when one of the variables is not a number. This will stop your program. We can easily overcome this as the next snippet shows.
let testnum = Number(prompt("Pick a number"));
if (!isNaN(testnum))
{
alert("The solution = " + testnum * 3);
}
else
{
alert("Your input is not a number");
}
The program will ask for a number. If you enter a number an alert will show the number x 3. If you enter a word or random letters the program wil generate an alert but it will not stop.
Using !isNaN() we can test wether the variable is indeed a number.
During a calculation an error wil be generated when one of the variables is not a number. This will stop your program. We can easily overcome this as the next snippet shows.
let testnum = Number(prompt("Pick a number"));
if (!isNaN(testnum))
{
alert("The solution = " + testnum * 3);
}
else
{
alert("Your input is not a number");
}
The program will ask for a number. If you enter a number an alert will show the number x 3. If you enter a word or random letters the program wil generate an alert but it will not stop.
Using !isNaN() we can test wether the variable is indeed a number.
Test if a variable is a number
To tewst wether a variable is a number or a string we can use the command typeof. Unfortunately this is not always reliable.
alert(typeof +"a10.1");
The alert will tell us that it is a number while a10.1 is not.
The accurate way to test wether a string is a number is as follows.
var value = "10.1";
if (Number.isNaN(+value))
{
alert ("Not a number");
}
else
{
alert ("Yes it is a number")
}
To tewst wether a variable is a number or a string we can use the command typeof. Unfortunately this is not always reliable.
alert(typeof +"a10.1");
The alert will tell us that it is a number while a10.1 is not.
The accurate way to test wether a string is a number is as follows.
var value = "10.1";
if (Number.isNaN(+value))
{
alert ("Not a number");
}
else
{
alert ("Yes it is a number")
}
Test if a variable is a number 2
Here is a fast way to test wether a variable is a number or a string.
var test = Number("Luc");
alert (test);
The variable test will give Nan (not a number) in the alert
Here is a fast way to test wether a variable is a number or a string.
var test = Number("Luc");
alert (test);
The variable test will give Nan (not a number) in the alert
Test for even or odd
Sometimes you need to test wether a number is even or odd. This can easily be done with the modulus function. When a number is divided by 2 and the remainder is 0 the number is even.
function iseven(number)
{
if (number%2 == 0)
return "even";
else
return "odd";
}
Call this function as follows:
alert(iseven(9));
Test for prime number
Prime numbers are used in computer science to encrypt data or passwords. It is beyond the scope of this book to explain how that is done, but you can find examples on the internet. The next bit of code tests wether a number is a prime number or not and gives true or false as the result.
function testifprime(value)
{
if (value===1)
{
return false;
}
if(value === 2)
{
return true;
}
if (value > 2)
{
for(var x = 2; x < value; x++)
{
if(value % x === 0)
{
return false;
}
}
return true;
}
}
alert(testifprime(4));
alert(testifprime(155035219));
Prime numbers are used in computer science to encrypt data or passwords. It is beyond the scope of this book to explain how that is done, but you can find examples on the internet. The next bit of code tests wether a number is a prime number or not and gives true or false as the result.
function testifprime(value)
{
if (value===1)
{
return false;
}
if(value === 2)
{
return true;
}
if (value > 2)
{
for(var x = 2; x < value; x++)
{
if(value % x === 0)
{
return false;
}
}
return true;
}
}
alert(testifprime(4));
alert(testifprime(155035219));
Underscore in a number
A peculiarity of Javascript is that it accepts an underscore as part of a number. Just try the next snippet.
var number = 1_000;
alert(5_5 * number);
The alert will give the right answer being 55000.
Here is another example.
var number = 1_0_0_0;
alert(5_5 * number);
This only works with integers.
A peculiarity of Javascript is that it accepts an underscore as part of a number. Just try the next snippet.
var number = 1_000;
alert(5_5 * number);
The alert will give the right answer being 55000.
Here is another example.
var number = 1_0_0_0;
alert(5_5 * number);
This only works with integers.
Use = as part of a calculation
Normally we use = to get a result. We can however also use = as part of a calculation.
var number1 = 100;
var number2 = 200;
var number2 = 300 - (number1 = number2/number1);
alert( number1 );
alert( number2 );
The calculation first assigns number2/number1 to variable number1 which then will be 2. Then variable 2 gets the value 300 - variable 1. So the alerts will show first 2 and then 298.
Normally we use = to get a result. We can however also use = as part of a calculation.
var number1 = 100;
var number2 = 200;
var number2 = 300 - (number1 = number2/number1);
alert( number1 );
alert( number2 );
The calculation first assigns number2/number1 to variable number1 which then will be 2. Then variable 2 gets the value 300 - variable 1. So the alerts will show first 2 and then 298.
Using switch-case with comparisons
It is not possible to use swithc-case statements with comparisons like < or > The next snippet shows how you can achieve that.
function maxspeed(kmperhour) {
var juistofniet = "";
switch (true) {
case isNaN(kmperhour):
withinlimit = "Wrong input";
break;
case (kmperhour > 100):
withinlimit = "too speedy";
break;
case (kmperhour <= 100):
withinlimit = "doing ok";
break;
default:
juistofniet = "hmmmm";
break;
};
return juistofniet;
}
alert(maxsnelheid(90)); // will return "Baby"
It is not possible to use swithc-case statements with comparisons like < or > The next snippet shows how you can achieve that.
function maxspeed(kmperhour) {
var juistofniet = "";
switch (true) {
case isNaN(kmperhour):
withinlimit = "Wrong input";
break;
case (kmperhour > 100):
withinlimit = "too speedy";
break;
case (kmperhour <= 100):
withinlimit = "doing ok";
break;
default:
juistofniet = "hmmmm";
break;
};
return juistofniet;
}
alert(maxsnelheid(90)); // will return "Baby"
Use + to convert a string into a number
If we want to add the values of two strings we can not do that with the + sign.
var a = "5";
var b = "2";
a + b will then be "52" the strings will be concatenated in stead of added.
There is the function Number() which will convert strings to numbers (watch the capital N):
Number(a) + Number(b) will give 7 as an answer just like we want.
You can also achieve this with the + sign. If you put a + in front of a string that string will be converted to a number:
+a + +b wil give 7 as an answer.
Other calculations like * and / will automatically convert strings to numbers.
If we want to add the values of two strings we can not do that with the + sign.
var a = "5";
var b = "2";
a + b will then be "52" the strings will be concatenated in stead of added.
There is the function Number() which will convert strings to numbers (watch the capital N):
Number(a) + Number(b) will give 7 as an answer just like we want.
You can also achieve this with the + sign. If you put a + in front of a string that string will be converted to a number:
+a + +b wil give 7 as an answer.
Other calculations like * and / will automatically convert strings to numbers.