Skillversitas

Number & Math in JavaScript

JavaScript provides the Number data type to handle all kinds of numeric values — from integers to decimals, positive to negative, and even Infinity and NaN. In addition, the Math object provides a wide range of ready-made math methods that are extremely useful for campus calculations such as computing a GPA, rounding scores, and randomly generating quiz questions.


The Number Data Type

In JavaScript, all numbers — whether integers or decimals — use the Number data type. There is no distinction like int and float in other languages.

// Integers
const semester = 4;
const creditsCount = 24;

// Decimals (floating point)
const gpa = 3.75;
const averageGrade = 82.5;

// Negative numbers
const gpaDifference = -0.25;

// Scientific notation
const courseCost = 5e7; // 50000000 (5 × 10^7)

// Special values
const takHingga = Infinity;
const notANumber = NaN;

Code Example

// === NUMBER METHODS ===

// parseInt — convert a string to an integer
const semesterStr = "5";
const semester = parseInt(semesterStr);
console.log(semester); // 5

// parseInt with a base
const hexValue = parseInt("1A", 16);
console.log(hexValue); // 26

// parseFloat — convert a string to a decimal
const ipkStr = "3.85";
const gpa = parseFloat(ipkStr);
console.log(gpa); // 3.85

// isNaN — check whether a value is NaN
console.log(isNaN("hello"));   // true
console.log(isNaN(123));       // false
console.log(isNaN(NaN));       // true

// isFinite — check whether a value is a finite number
console.log(isFinite(100));        // true
console.log(isFinite(Infinity));   // false
console.log(isFinite("100"));      // true (auto-converts)

// Number.isInteger — check whether it is an integer
console.log(Number.isInteger(5));      // true
console.log(Number.isInteger(5.5));    // false
console.log(Number.isInteger("5"));    // false (no auto-conversion)

Number Formatting

const examGrade = 87.654;

// toFixed(n) — format with n digits after the decimal point
console.log(examGrade.toFixed(2));  // "87.65"
console.log(examGrade.toFixed(0));  // "88" (rounded)
console.log(examGrade.toFixed(1));  // "87.7"

// toPrecision(n) — n significant digits in total
console.log(examGrade.toPrecision(4));  // "87.65"
console.log(examGrade.toPrecision(2));  // "88"

// toExponential(n) — scientific notation format
const amount = 1250000;
console.log(amount.toExponential(2));  // "1.25e+6"

Code Example: The Math Object

// === MATH OBJECT ===

// Math.abs — absolute value
const difference = Math.abs(85 - 92);
console.log(difference); // 7

// Math.ceil — round up
console.log(Math.ceil(82.1));  // 83
console.log(Math.ceil(82.9));  // 83

// Math.floor — round down
console.log(Math.floor(82.9));  // 82
console.log(Math.floor(82.1));  // 82

// Math.round — round to the nearest
console.log(Math.round(82.5));  // 83
console.log(Math.round(82.4));  // 82

// Math.max & Math.min
const midTermGrade = [78, 92, 85, 90, 88];
console.log(Math.max(...midTermGrade));  // 92
console.log(Math.min(...midTermGrade));  // 78

// Math.random — random number from 0 (inclusive) to 1 (exclusive)
console.log(Math.random()); // example: 0.7384921

// Math.pow — exponentiation
console.log(Math.pow(2, 10));  // 1024

// Math.sqrt — square root
console.log(Math.sqrt(144));   // 12

// Math.PI
console.log(Math.PI); // 3.141592653589793

Code Explanation

Method Function Example Output
parseInt() String → integer parseInt("42") → 42
parseFloat() String → float parseFloat("3.14") → 3.14
isNaN() Check isNaN isNaN("abc") → true
isFinite() Check finite isFinite(100) → true
toFixed(n) Format a decimal (3.14).toFixed(1) → "3.1"
Math.ceil() Round up Math.ceil(4.2) → 5
Math.floor() Round down Math.floor(4.8) → 4
Math.random() Random number 0-1 0.738...

Difference between parseInt() and Number():
- parseInt("42px") → 42 (ignores non-numeric characters at the end)
- Number("42px") → NaN (the entire string must be numeric)


Everyday Case Studies

1. Calculating and Formatting a GPA

// Grade transcript data
const transcript = [
  { course: "Algorithms", credits: 3, grade: "A" },
  { course: "Database", credits: 3, grade: "B+" },
  { course: "Web Dev", credits: 4, grade: "A-" },
  { course: "Statistics", credits: 3, grade: "B" },
];

// Mapping grades to numeric values
const weightGrade = {
  "A": 4.0, "A-": 3.7, "B+": 3.3, "B": 3.0,
  "B-": 2.7, "C+": 2.3, "C": 2.0, "D": 1.0, "E": 0
};

let totalCredits = 0;
let totalWeight = 0;

for (const course of transcript) {
  const credits = course.credits;
  const weight = weightGrade[course.grade];
  totalCredits += credits;
  totalWeight += credits * weight;
}

const gpa = totalWeight / totalCredits;

console.log(`GPA: ${gpa.toFixed(2)}`);        // "GPA: 3.43"
console.log(`Total credits: ${totalCredits}`);          // "Total credits: 13"
console.log(`Classification: ${gpa >= 3.5 ? "Cum Laude" : "Very Satisfactory"}`);

2. Random Quiz Generator

// Question bank
const questionBank = [
  "What does HTML stand for?",
  "What is CSS used for?",
  "Sebutkan 3 primitive type di JavaScript!",
  "What is the DOM in web development?",
  "What is the difference between var, let, and const?",
  "What does API stand for?",
  "What is JSON?",
  "Sebutkan method array di JavaScript!",
];

// Pick random questions (without repetition)
function generateQuiz(questionCount) {
  const selectedQuestions = [];
  const remainingQuestions = [...questionBank]; // copy the array

  const effectiveCount = Math.min(questionCount, remainingQuestions.length);

  for (let i = 0; i < effectiveCount; i++) {
    const randomIndex = Math.floor(Math.random() * remainingQuestions.length);
    selectedQuestions.push(remainingQuestions[randomIndex]);
    remainingQuestions.splice(randomIndex, 1);
  }

  return selectedQuestions;
}

// Generate 3 random questions for a quiz
const weeklyQuiz = generateQuiz(3);
weeklyQuiz.forEach((question, index) => {
  console.log(`Question ${index + 1}:  ${question}`);
});

// Generate a random exam number
function generateExamNumber(semester, year) {
  const randomPart = Math.floor(Math.random() * 10000);
  return `${year}${semester}${String(randomPart).padStart(4, "0")}`;
}

console.log(generateExamNumber(4, "2022")); // example: "202243847"

3. Dividing Lab Practice Groups

const countStudent = 35;
const groupCount = 6;

// Calculate the distribution
const membersPerGroup = Math.floor(countStudent / groupCount);
const remaining = countStudent % groupCount;

console.log(`Student per group: ${membersPerGroup}`); // 5
console.log(`Remaining (group extra): ${remaining}`);               // 5

// Create an even distribution
const distribution = [];
let student = 1;

for (let i = 0; i < groupCount; i++) {
  const count = i < remaining ? membersPerGroup + 1 : membersPerGroup;
  const member = [];
  for (let j = 0; j < count; j++) {
    member.push(student++);
  }
  distribution.push({ group: i + 1, member });
}

distribution.forEach(k => {
  console.log(`Group ${k.group}: ${k.member.length} people`);
});

Conclusion

  • All numbers in JavaScript are of type Number — there is no int vs float distinction.
  • Use parseInt() to extract integers from strings, and parseFloat() for decimals.
  • isNaN() is useful for input validation, and Number.isInteger() for checking integers.
  • toFixed(), toPrecision(), and toExponential() are for formatting number display.
  • The Math object provides basic math methods: abs, ceil, floor, round, random, max, min, pow, and sqrt.
  • Math.random() is extremely useful for randomization needs — from quiz generators to group division.