Javascript – Numbers

Numbers are binary base in javascript

+ works the same as Number():

Number('23')
+('23)

Number.parseInt(string, redex)

Turns string into integer if it starts with a number (removing any other characters in the string. Redex not neccessary

Number.parseInt('20px', 10) // returns 20
Number.parseInt('e20', 10) // returns NaN

Number.parseFloat(string, redex)

parseFloat is used if the number has a decimal place.

Number.isNaN(string)

Boolean to check if it is not a number

Number.isFinite(), Number.isInteger()

Better to use than isNaN. To check if it is a number as it can check if numbers are divided by 0.

Math

Math.sqrt*(); Square root
Math.max(array) // Returns maximum number in array (does string to number converstion)
Math.min(array) // Returns minimum in array

Math.PI + Number.parseFloat(radius) ++2)

//Random
Math.trunc.random() * 6) + 1); // gets a number between 1 and 6

// Random Function
const randomInt = (min, max) => Math.floor(random() * (min-max + 1) + min)
console.log(randomInt(10,20));

// Rounding Integers
Math.trunc(23.3) // removes the decimal values
Math.round() // round to nearest
Math.ceil() // round up
Math.floor() // round down

// Rounding decimals
(value).toFixed(nummber of decimal places) // !!! Returns String
+(2.345).toFixed(2) // returns 2.34

Remainder operator

returns the remainder of a division

5 % 2 // returns 1

Numeric Seperator

Use _, js will ignore it and convert the number fully.

BigInt

JS has 53 bytes for integers, so there is a limit to the highest number that can be used

Number.MAX_SAFE_INTEGER

Use n at the end of a very lager number or use BigInt()

Cannot mix BigInts with regular numbers (except on < or >) (convert number to bigInt). Math operations will not work either.

Leave a Reply

Your email address will not be published. Required fields are marked *