Numbers in JavaScript (Number type) are used for various tasks. These include counting integers, physics calculations, defining colors, and bit manipulation. This article explains calculation methods using the Math object, different base notations to improve code readability, and the limit values for numbers. Use the provided code to solidify your understanding of numerical processing.
Specifications (Input/Output)
Type
Description
Input
Numerical data such as game parameters, file permissions, and color codes.
Output
Calculation results from Math functions, decimal values from base literals, and Number type constants.
Basic Usage
To perform advanced calculations, use the methods of the Math class. When writing numbers in your code, you can use prefixes like 0x to define values in the base that fits your specific needs.
Key Methods of the Math Object
Category
Method
Example
Description
Basic Math
Math.abs(x)
Math.abs(-50)
Returns the absolute value (50).
Power/Root
Math.pow(x, y)
Math.pow(2, 10)
Returns x to the power of y (1024).
Rounding
Math.round(x)
Math.round(4.7)
Rounds to the nearest integer (5).
Trigonometry
Math.sin(x)
Math.sin(Math.PI/2)
Calculates the sine value.
Randomness
Math.random()
Math.random()
Generates a random decimal between 0 and 1.
Full Code (HTML / JavaScript)
HTML (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Number Handling</title>
<script src="math-logic.js" defer></script>
</head>
<body>
<div class="container">
<h1>Check Calculation Results</h1>
<p>Open the console (F12) to check the logs.</p>
</div>
</body>
</html>
JavaScript (math-logic.js)
/**
* Demonstration of numerical operations and logic
*/
const executeNumberLogic = () => {
console.log('--- 1. Calculations with the Math Object ---');
// Parameters for a game scenario
const playerX = 150;
const playerY = 200;
const enemyX = 100;
const enemyY = 250;
const criticalRate = 0.5; // 50%
const damageDiff = -45; // Damage variation (negative value)
// [Mathematical Calculation] Find the distance using the Pythagorean theorem
const distance = Math.sqrt(Math.pow(playerX - enemyX, 2) + Math.pow(playerY - enemyY, 2));
console.log(`Distance to enemy: ${distance.toFixed(2)}`);
// [Absolute Value] Get the magnitude regardless of the sign
console.log(`Damage variation magnitude: ${Math.abs(damageDiff)}`);
// [Rounding] Converting decimals to integers for UI displays
const rawHP = 98.76;
console.log(`Round HP: ${Math.round(rawHP)}`); // 99
console.log(`Ceil HP (Up): ${Math.ceil(rawHP)}`); // 99
console.log(`Floor HP (Down): ${Math.floor(rawHP)}`); // 98
// [Randomness] Judging a critical hit
const isCritical = Math.random() < criticalRate;
console.log(`Critical Hit: ${isCritical ? "Occurred!" : "Normal"}`);
console.log('--- 2. Base Literal Notations and Use Cases ---');
// Using the best notation for each purpose
const filePermission = 0o644; // Octal (UNIX file permissions)
const colorGreen = 0x00FF00; // Hexadecimal (RGB color code)
const bitFlag = 0b1010; // Binary (Bitmask/Flag management)
const normalCount = 999; // Decimal (Standard count)
// Values are converted to decimal automatically when output
console.table([
{ type: "Octal", literal: "0o644", value: filePermission },
{ type: "Hex", literal: "0x00FF00", value: colorGreen },
{ type: "Binary", literal: "0b1010", value: bitFlag },
{ type: "Decimal", literal: "999", value: normalCount },
]);
console.log('--- 3. Checking Limit Constants ---');
// Check system limits to prevent overflow
console.table({
"MAX_VALUE": Number.MAX_VALUE,
"MIN_VALUE": Number.MIN_VALUE,
"MAX_SAFE_INTEGER": Number.MAX_SAFE_INTEGER,
"MIN_SAFE_INTEGER": Number.MIN_SAFE_INTEGER
});
};
// Execute
executeNumberLogic();
Customization Points
Base Notation Reference
Notation
Prefix
Example
Practical Use Case
Decimal
None
255, 100
General calculations, loop counts.
Hexadecimal
0x
0xFF, 0xA1
Color codes, memory addresses, character codes.
Octal
0o
0o644
Linux/Unix file permissions.
Binary
0b
0b1010
Bit flags, on/off state management.
Number Object Constants
Constant
Meaning
Approximate Value / Range
Number.MAX_VALUE
Largest representable floating-point number.
1.79e+308
Number.MIN_VALUE
Smallest positive number closest to zero.
5.00e-324
Number.MAX_SAFE_INTEGER
Max integer for safe precision.
9,007,199,254,740,991
Number.MIN_SAFE_INTEGER
Min integer for safe precision.
-9,007,199,254,740,991
Important Points
Issue
Description
Solution
Rounding Errors
Decimal math like 0.1 + 0.2 contains small errors.
Multiply by 100 to work with integers and divide at the end.
Integer Overflow
Calculations above MAX_SAFE_INTEGER are inaccurate.
Use the BigInt type (e.g., 100n).
Division by Zero
Dividing by zero returns Infinity instead of an error.
Validate that the divisor is not zero before calculating.
Advanced Usage
Restricting Values within a Range (Clamping)
You can restrict a value to a specific range (e.g., 0 to 100) by combining Math.min and Math.max.
Processing numbers in JavaScript requires more than just basic arithmetic; precise Math object methods and an understanding of underlying system constraints are essential. By utilizing base notations for domain-specific clarity and monitoring constant limits, you can ensure that your calculations remain accurate and performant. Mastering these techniques is the foundation for building complex logic in scientific and interactive applications.