Javascript
/
Types
- 1 Fundamentals 11
-
Hello World S
-
Code structure S
-
Use strict S
-
Variables S
-
Data types S
-
Type conversions S
-
Maths S
-
Comparitions S
-
Conditional S
-
Loops S
-
Functions S
- 2 Testing 2
-
Mocha S
-
Nested describe S
- 3 Objects 4
-
Basics S
-
Reference S
-
Methods S
-
Constructor S
- 4 Types 5
-
Primitives S
-
Numbers S
-
Strings S
-
Arrays S
-
Json S
- 5 Classes 3
-
Constructor S
-
Binding S
-
Inheritance S
S
R
Q
Javascript Types Numbers
Built-in functions for rounding Losing precision, true for many languages let sum = 0.1 + 0.2; sum == 0.30000000000000004 sum.toFixed(2) === "0.30"
Round
One of the most used operations, when working with numbers, is rounding.
/**
* Several built-in functions for rounding
*/
let n = 1.23456;
let a = Math.round(n * 100) / 100; // 123 -> 1.23
let b = n.toFixed(2); // "1.23"
console.log(a); // 1.23
console.log(1.23 === b); // false
Precision
Internally, a number is represented in a 64-bit format.
/**
* Losing precision is quite common
* and this is true for many other languages
*
* There are exactly 64 bits to store a number:
* 52 to store the digits
* 11 to store the position of decimal point
* 1 bit for the sign
*/
let sum = 0.1 + 0.2;
console.log(sum); // 0.30000000000000004
console.log(sum.toFixed(2) === "0.30"); // true
console.log(+sum.toFixed(2) === 0.3); // true (unary + converts to number)
Conversion
Parse functions read a number from a string, until they can't.
/**
* In real life, values like "100px" or "19$"
*
* parseInt() returns integer
* parserFloat() returns floating-point number
*/
console.log(parseInt("100px") === 100); // true
console.log(parseInt("19$") === 19); // true
console.log(parseFloat("12.3") === 12.3); // true
console.log(parseFloat("12.3.4") === 12.3); // true
// 12.3 second point stop reading
➥ Questions