[JavaScript] Practical Numerical Calculation Techniques and Base Literal/Constant Reference

目次

Overview

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)

TypeDescription
InputNumerical data such as game parameters, file permissions, and color codes.
OutputCalculation 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

CategoryMethodExampleDescription
Basic MathMath.abs(x)Math.abs(-50)Returns the absolute value (50).
Power/RootMath.pow(x, y)Math.pow(2, 10)Returns x to the power of y (1024).
RoundingMath.round(x)Math.round(4.7)Rounds to the nearest integer (5).
TrigonometryMath.sin(x)Math.sin(Math.PI/2)Calculates the sine value.
RandomnessMath.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

NotationPrefixExamplePractical Use Case
DecimalNone255, 100General calculations, loop counts.
Hexadecimal0x0xFF, 0xA1Color codes, memory addresses, character codes.
Octal0o0o644Linux/Unix file permissions.
Binary0b0b1010Bit flags, on/off state management.

Number Object Constants

ConstantMeaningApproximate Value / Range
Number.MAX_VALUELargest representable floating-point number.1.79e+308
Number.MIN_VALUESmallest positive number closest to zero.5.00e-324
Number.MAX_SAFE_INTEGERMax integer for safe precision.9,007,199,254,740,991
Number.MIN_SAFE_INTEGERMin integer for safe precision.-9,007,199,254,740,991

Important Points

IssueDescriptionSolution
Rounding ErrorsDecimal math like 0.1 + 0.2 contains small errors.Multiply by 100 to work with integers and divide at the end.
Integer OverflowCalculations above MAX_SAFE_INTEGER are inaccurate.Use the BigInt type (e.g., 100n).
Division by ZeroDividing 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.

const clamp = (val, min, max) => Math.min(Math.max(val, min), max);

const hp = 150;
const validHP = clamp(hp, 0, 100); 
console.log(validHP); // Outputs 100

Summary

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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次