toFixed() is a
Number method that is used to convert a number to fixed-point notation (rounding the result where necessary) and returns the value as a string:
decimalPlaces is optional, and defines the number of digits that should be present after the decimal place and defaults to
let number = 12345.6789 console.log(number.toFixed()) // Returns '12346': note rounding, no fractional part console.log(number.toFixed(1)) // Returns '12345.7': note rounding console.log(number.toFixed(6)) // Returns '12345.678900': note added zeros console.log((1.23e+20).toFixed(3)) // Returns '123000000000000000000.000'
If the floating-point number didn't offer precision up to the fixed point you're formatting to - 0s are added as padding to the end.
toPrecision() is a
Number method that formats a number to a precision string - keeping track of how many total digits (including digits to the left and right of the decimal) to display of a number:
significantDigits is optional, denoting the number of significant digits to display in the result. If omitted, the method just converts the number to a string.
let number = 5.123456 console.log(number.toPrecision()) // logs '5.123456' console.log(number.toPrecision(5)) // logs '5.1235' number = 0.000123 console.log(number.toPrecision()) // logs '0.000123' console.log(number.toPrecision(5)) // logs '0.00012300'
The returned values are of
console.log(typeof number.toPrecision()) // string
toPrecision() method will pad the resulting value with 0's if there are not enough significant digits, and it does not change the value of the original number - it returns a new result.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
fractionalDigits as an argument is optional, and specifies how many fractional digits are to be displayed in the result. If this argument is missing, the output may contain up to 16 fractional digits, depending on your browser:
let number = 95.3434; console.log(number.toExponential()); // 9.53434e+1 console.log(number.toExponential(4)); // 9.5343e+1 console.log(number.toExponential(2)); // 9.53e+1 console.log(95.3434.toExponential()); // 9.53434e+1
toExponential() method does not change the value of the original number - it returns a new value to be stored.
toPrecision() methods of the