JavaScript tutorial : number method | toFixed | toPrecision
Today we will discuss the number method, toFixed, and toPrecission. Follow the comments and then practice. You can also copy and paste the code to your projects.
[code lang=”js”]
var num = 20
var text = "Riaj Ahmed";
var logic = true;
var decimal = 20.25632;
// To check the types of data in JS
console.log(typeof(num));
console.log(typeof(text));
console.log(typeof(logic));
console.log(typeof(decimal));
// To change the data type in JS
// To change number to string
var num = toString(num);
console.log(typeof(num));
// To change string to number
var text = parseInt(text);
console.log(typeof(text));
// To Change float to number.
var decimal = parseFloat(decimal);
console.log(typeof(decimal));
// use of tofixed
// How to change decimal to intiger
// Without decimal point
console.log(decimal.toFixed());
console.log(typeof(decimal));
// With one decimal point
console.log(decimal.toFixed(1));
// With two decimal point
console.log(decimal.toFixed(2));
// How to use to precision
// To show all the numbers
console.log(decimal.toPrecision());
// To show total 3 numbers
console.log(decimal.toPrecision(3));
/**
* Difference between toFixed and toPrecision
* toFixed shows numbers after decimal point
* but, toPrecision shows numbers from total numbers
*/
console.log(typeof(Number(text)));
console.log(Number(true));
console.log(typeof(Number(true)));
console.log(Number(false));
console.log(typeof(Number("5235.3")));
console.log(Number(" 123 "));
[/code]