In JavaScript, numbers can be written with or without decimals. For example, 42
and 3.14
are both valid numbers in JavaScript. Numbers in JavaScript are stored as 64-bit floating-point numbers, which means they have limited precision.
Here are some basic arithmetic operations you can perform with numbers in JavaScript:
- Addition:
x + y
- Subtraction:
x - y
- Multiplication:
x * y
- Division:
x / y
- Modulus (remainder after division):
x % y
Here's an example of how to use these operators:
let x = 10;
let y = 5;
console.log(x + y); // 15
console.log(x - y); // 5
console.log(x * y); // 50
console.log(x / y); // 2
console.log(x % y); // 0
In addition to basic arithmetic, JavaScript provides a number of built-in methods for working with numbers. Here are a few examples:
toFixed
: Rounds a number to a specified number of decimal places and returns a string.
let x = 3.14159265359;
console.log(x.toFixed(2)); // "3.14"
isNaN
: Returns true if a value is not a number.
console.log(isNaN(42)); // false
console.log(isNaN('Hello')); // true
parseInt
/parseFloat
: Converts a string to a number.
console.log(parseInt('42')); // 42
console.log(parseFloat('3.14')); // 3.14
Math.max
/Math.min
: Returns the highest or lowest value in a list of numbers.
console.log(Math.max(10, 20, 30)); // 30
console.log(Math.min(10, 20, 30)); // 10
Math.random
: Generates a random number between 0 and 1.
console.log(Math.random()); // 0.123456789...
These are just a few examples of the many methods available for working with numbers in JavaScript. By using them, you can perform complex mathematical operations and manipulate numbers in a variety of ways.
-
Video: "JavaScript Numbers | JavaScript Full Tutorial" https://www.youtube.com/watch?v=0ELC8R69Rkw (opens in a new tab)
-
Article: "JavaScript Number" https://www.programiz.com/javascript/numbers (opens in a new tab)