toFixed() Method - convert number to string with fixed number of decimal places


Thu Jan 09 2020 19:00:00 GMT+0000 (UTC)

Saved by @goblindoom95 #javascript #jsfunctions #numbers

var x = 1.2345;

var y = x.toFixed(0);
//y equals 1;

var y = x.toFixed(2);
//y equals 1.23

var y = x.toFixed(5);
//y equals 1.23400

line 1: assign a number value to the variable x lines 3+6+9: The number in the brackets - the parameter - defines the number of decimal places to display the number value of x. The method converts the value of x to a string with fixed decimal places and stores it in a new variable y. NOTE: it is not necessary to store the value of toFixed() in a new variable. RECOMMENDATIONS: Use 0 as a parameter to round off numbers to a whole number. Use 2 when rounding off numbers for money.