Join Regular Classroom : Visit ClassroomTech

JavaScript – codewindow.in

Related Topics

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

JAVASCRIPT

const number = 3.14159265359;
const roundedNumber = number.toFixed(2); // Limit to 2 decimal places
console.log(roundedNumber); // Output: "3.14"
Please note that toFixed() returns a string, so you might need to convert it back to a number if you need to perform further calculations.
  1. Using Math.round(), Math.floor(), or Math.ceil(): You can also use these methods in combination with multiplication and division to round the number to a specific number of decimal places.
  • Math.round(): Rounds to the nearest integer.
  • Math.floor(): Rounds down to the nearest integer.
  • Math.ceil(): Rounds up to the nearest integer.
const number = 3.14159265359;
const roundedNumber = Math.round(number * 100) / 100; // Limit to 2 decimal places
console.log(roundedNumber); // Output: 3.14
Using parseFloat() and toFixed(): If you prefer to keep the result as a number (not a string), you can combine parseFloat() with toFixed() to limit the number of decimal places.
const number = 3.14159265359;
const roundedNumber = parseFloat(number.toFixed(2)); // Limit to 2 decimal places
console.log(roundedNumber); // Output: 3.14
Keep in mind that these methods round or truncate the number and may introduce small rounding errors due to the limitations of representing floating-point numbers in JavaScript. If precise decimal arithmetic is required, consider using external libraries like BigDecimal.js or decimal.js.
Choose the method that best suits your use case and the level of precision required for your application.
const minResult = Math.min(10, 5, 2, 20, 8);
console.log(minResult); // Output: 2
Using an array:
const numbers = [10, 5, 2, 20, 8];
const minResult = Math.min(...numbers);
console.log(minResult); // Output: 2
  1. Math.max(): The Math.max() function returns the largest (maximum) numeric value from a set of arguments or an array. Like Math.min(), it also accepts multiple arguments or an array of numbers.
Using multiple arguments:
const maxResult = Math.max(10, 5, 2, 20, 8);
console.log(maxResult); // Output: 20
Using an array:
const numbers = [10, 5, 2, 20, 8];
const maxResult = Math.max(...numbers);
console.log(maxResult); // Output: 20
It’s important to note that both Math.min() and Math.max() return the actual numeric values, not their indices in the array. If you need to get the index of the minimum or maximum value in an array, you’ll have to perform additional logic.
const numbers = [10, 5, 2, 20, 8];
const minValue = Math.min(...numbers);
const minIndex = numbers.indexOf(minValue);
console.log(minIndex); // Output: 2 (index of the minimum value)
Both Math.min() and Math.max() also support variable-length arguments, which means you can pass any number of values separated by commas.
const minValue = Math.min(10, 5, 2, 20, 8);
const maxValue = Math.max(10, 5, 2, 20, 8);
console.log(minValue); // Output: 2
console.log(maxValue); // Output: 20
In summary, Math.min() returns the smallest value from a set of numbers, and Math.max() returns the largest value from a set of numbers. They are both handy functions when you need to find minimum and maximum values without manually iterating through an array or list of numbers.
console.log(Number.isInteger(42)); // Output: true
console.log(Number.isInteger(3.14)); // Output: false
console.log(Number.isInteger(0)); // Output: true
console.log(Number.isInteger(-10)); // Output: true
console.log(Number.isInteger("42")); // Output: false (not a number, but a string)
console.log(Number.isInteger(NaN)); // Output: false (NaN is not an integer)
Using the Number.isSafeInteger() method: The Number.isSafeInteger() method checks if a given value is a safe integer in JavaScript. A safe integer is an integer that can be exactly represented as a 53-bit (including the sign bit) two’s complement binary representation without losing precision. This method returns true for safe integers and false for non-safe integers or non-numeric values.
console.log(Number.isSafeInteger(42)); // Output: true
console.log(Number.isSafeInteger(Math.pow(2, 53))); // Output: false (2^53 is not a safe integer)
console.log(Number.isSafeInteger("42")); // Output: false (not a number, but a string)
console.log(Number.isSafeInteger(NaN)); // Output: false (NaN is not a safe integer)
Using modulo operator: Another way to check if a number is an integer is to use the modulo operator %. An integer divided by 1 will always have a remainder of 0. So, you can check if the remainder is 0 to determine if the number is an integer.
function isInteger(number) {
  return number % 1 === 0;
}

console.log(isInteger(42)); // Output: true
console.log(isInteger(3.14)); // Output: false
console.log(isInteger(0)); // Output: true
console.log(isInteger(-10)); // Output: true
console.log(isInteger("42")); // Output: false (not a number, but a string)
console.log(isInteger(NaN)); // Output: false (NaN is not an integer)
All three methods mentioned above can be used to determine if a number is an integer in JavaScript. The Number.isInteger() method is the most straightforward and recommended way for this purpose, as it specifically checks for integers and works consistently across different JavaScript implementations.
number.toFixed(digits)
Here, number is the number you want to format, and digits is an optional parameter specifying the number of decimal places you want in the resulting string. If digits is not provided or is 0, toFixed() will return the number formatted as an integer (no decimal places).
Let’s see some examples of using toFixed():
const number1 = 3.14159;
const formattedNumber1 = number1.toFixed(2);
console.log(formattedNumber1); // Output: "3.14"

const number2 = 42;
const formattedNumber2 = number2.toFixed(3);
console.log(formattedNumber2); // Output: "42.000"

const number3 = 2.71828;
const formattedNumber3 = number3.toFixed(0);
console.log(formattedNumber3); // Output: "3"
A few things to note about the toFixed() method:
  1. The result is always returned as a string, even if the number has no decimal places or is an integer.
  2. If the number has more decimal places than specified by digits, toFixed() will round the number to the specified number of decimal places.
const number4 = 1.99999;
const formattedNumber4 = number4.toFixed(2);
console.log(formattedNumber4); // Output: "2.00" (rounded up to two decimal places)
  1. The method also adds trailing zeros if needed to reach the specified number of decimal places.
const number5 = 5;
const formattedNumber5 = number5.toFixed(3);
console.log(formattedNumber5); // Output: "5.000" (added trailing zeros to reach three decimal places)
  1. If the original number is not finite (e.g., Infinity, -Infinity, or NaN), toFixed() will throw a RangeError.
const number6 = Infinity;
const formattedNumber6 = number6.toFixed(2); // Throws RangeError
It’s important to be aware that using toFixed() returns a string representation of the number, not a numeric value. If you need to perform further mathematical calculations, you may need to convert the formatted string back to a number using functions like parseFloat() or Number().
const stringNumber = "42";
const integerNumber = parseInt(stringNumber);
console.log(integerNumber); // Output: 42 (converted to an integer)

const floatNumber = parseFloat("3.14");
console.log(floatNumber); // Output: 3.14 (converted to a floating-point number)
The parseInt() function can also take an optional second argument, called the radix, which specifies the base of the number system used in the string.
const binaryNumber = parseInt("101010", 2); // Convert binary string to integer
console.log(binaryNumber); // Output: 42
2. Using the unary plus operator +: The unary plus operator can be used to convert a string containing a numeric value (integer or floating-point) into a number.
const stringNumber = "42";
const numericValue = +"42";
console.log(numericValue); // Output: 42 (converted to a number)
3.  Using Number() constructor: The Number() constructor can be used to explicitly convert a string into a number. It behaves similarly to the unary plus operator.
const stringNumber = "42";
const numericValue = Number(stringNumber);
console.log(numericValue); // Output: 42 (converted to a number)
It’s important to note that when the string contains non-numeric characters, all these methods will return NaN (Not-a-Number).
const nonNumericString = "Hello";
const result = parseInt(nonNumericString);
console.log(result); // Output: NaN (cannot parse "Hello" as a number)
When using parseInt() or parseFloat(), make sure to handle invalid conversions by checking if the result is NaN using the isNaN() function or the Number.isNaN() method.
const result = parseInt("Hello");
if (isNaN(result)) {
  console.log("Invalid number");
} else {
  console.log("Parsed number:", result);
}
Choose the appropriate method based on your specific use case, and ensure proper error handling when dealing with non-numeric strings to avoid unexpected results.
console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.round(3.6)); // Output: 4
console.log(Math.floor(3.6)); // Output: 3
console.log(Math.ceil(3.6)); // Output: 4
console.log(Math.sin(Math.PI / 2)); // Output: 1 (sine of 90 degrees)
console.log(Math.exp(2)); // Output: 7.3890560989306495 (e^2)
console.log(Math.random()); // Output: Random number between 0 and 1
The Math object is a powerful tool for performing mathematical operations in JavaScript and is commonly used in a wide range of applications, including calculations, geometry, statistics, and random number generation.
const angleInRadians = Math.PI / 6; // 30 degrees in radians
const sineValue = Math.sin(angleInRadians);
console.log(sineValue); // Output: 0.5 (sin(π/6) = 0.5)
  1. Math.cos(x): Returns the cosine of the angle x.
const angleInRadians = Math.PI / 3; // 60 degrees in radians
const cosineValue = Math.cos(angleInRadians);
console.log(cosineValue); // Output: 0.5 (cos(π/3) = 0.5)
  1. Math.tan(x): Returns the tangent of the angle x.
const angleInRadians = Math.PI / 4; // 45 degrees in radians
const tangentValue = Math.tan(angleInRadians);
console.log(tangentValue); // Output: 1 (tan(π/4) = 1)
  1. Math.asin(x): Returns the arcsine (inverse sine) of x, in radians.
const sineValue = 0.5;
const angleInRadians = Math.asin(sineValue);
console.log(angleInRadians); // Output: 0.5235987755982988 (arcsin(0.5) = π/6)
  1. Math.acos(x): Returns the arccosine (inverse cosine) of x, in radians.
const cosineValue = 0.5;
const angleInRadians = Math.acos(cosineValue);
console.log(angleInRadians); // Output: 1.0471975511965976 (arccos(0.5) = π/3)
  1. Math.atan(x): Returns the arctangent (inverse tangent) of x, in radians.
const tangentValue = 1;
const angleInRadians = Math.atan(tangentValue);
console.log(angleInRadians); // Output: 0.7853981633974483 (arctan(1) = π/4)
Remember to convert angles to radians when using trigonometric functions, and convert them back to degrees if needed.
It’s also important to note that trigonometric functions may introduce small rounding errors due to the limitations of representing floating-point numbers in JavaScript. For precise trigonometric calculations, consider using external libraries or implementing more advanced algorithms.
console.log(Math.abs(5));    // Output: 5 (positive number remains unchanged)
console.log(Math.abs(-7));   // Output: 7 (negative sign is removed)
console.log(Math.abs(0));    // Output: 0 (absolute value of 0 is 0)
console.log(Math.abs(-3.14)); // Output: 3.14 (negative sign is removed)
2. Math.ceil(x): The Math.ceil() method rounds a number x up to the nearest integer that is greater than or equal to x. It returns the smallest integer greater than or equal to the original number.
console.log(Math.ceil(3.14));   // Output: 4 (rounds up to the nearest integer)
console.log(Math.ceil(7.99));   // Output: 8 (rounds up to the nearest integer)
console.log(Math.ceil(10));     // Output: 10 (no rounding needed, already an integer)
console.log(Math.ceil(-2.75));  // Output: -2 (rounds up to the nearest integer)
3. Math.floor(x): The Math.floor() method rounds a number x down to the nearest integer that is less than or equal to x. It returns the largest integer less than or equal to the original number.
console.log(Math.floor(3.14));   // Output: 3 (rounds down to the nearest integer)
console.log(Math.floor(7.99));   // Output: 7 (rounds down to the nearest integer)
console.log(Math.floor(10));     // Output: 10 (no rounding needed, already an integer)
console.log(Math.floor(-2.75));  // Output: -3 (rounds down to the nearest integer)
The ceil() and floor() methods are particularly useful when you need to ensure a number is rounded up or down to a whole number or the nearest integer for various purposes like pagination, rendering elements on a grid, or positioning elements in a layout.
For more advanced rounding or formatting requirements (e.g., specific decimal precision), you can use the toFixed() method or custom functions in combination with these methods.

      

Popular Category

Topics for You

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

Go through our study material. Your Job is awaiting.

Recent Posts
Categories