Showing posts with label Min. Show all posts
Showing posts with label Min. Show all posts

2023-05-10

Javascript :: Math round, ceiling (ceil), floor, max, min, random, etc...

It's common to try to remember what's the right call for Math functions, hence adding this to my local KB here.

Always the same principle, Math.function(<params>).

Round:
var a = 123.45;
var b = 345.67;
console.log(Math.round(a));
console.log(Math.round(b));
//outputs: 123
//outputs: 346


Ceiling (ceil):
var a = 123.45;
var b = 345.67;
console.
log(Math.ceil(a));
console.log(Math.ceil(b));
//outputs: 124
//outputs: 346

Floor:
var a = 123.45;
var b = 345.67;
console.
log(Math.floor(a));
console.log(Math.floor(b));
//outputs: 123
//outputs: 345

Max:
var a = 123.45;
var b = 345.67;
console.
log(Math.max(a, b));
//outputs: 345.67

Min:
var a = 123.45;
var b = 345.67;
console.
log(Math.min(a, b));
//outputs: 123.45

Random:
function getRandomInteger(limitIntValue) {
  return Math.round(Math.random() * limitIntValue);
}
function getRandomNumber(limitNumberValue) {
  return (Math.random() * limitNumberValue);
}
console.log(getRandomInteger(10));
console.log(getRandomInteger(-10));
console.log(getRandomNumber(123.45));
//outputs: <random integer value between 0 and 10>
//outputs: <random integer value between -10 and 0>
//outputs: <random number value between 0 and 123.45>


Javascript :: comparison operators, using == vs === and != vs !==

Comparison operators are distinguished following simple logic, whether data type is being included or not. Essentially if it is === or !==, ...