6.5 Number MethodsNumber Methods and PropertiestoString MethodtoExponential MethodtoFixed MethodtoPrecision MethodvalueOf MethodNumber MethodPrevious Section
6.5 Number Methods
Number Methods and Properties
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
toString
Method
The
toString
method returns a number as a string.All number methods can be used on any type of numbers (literals, variables, or expressions):
let x = 123; x.toString(); // returns 123 from variable x (123).toString(); // returns 123 from literal 123 (100 + 23).toString(); // returns 123 from expression 100 + 23
toExponential
Method
toExponential()
returns a string, with a number rounded and written using exponential notation.A parameter defines the number of characters behind the decimal point:
let x = 9.656; x.toExponential(2); // returns 9.66e+0 x.toExponential(4); // returns 9.6560e+0 x.toExponential(6); // returns 9.656000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the number.
toFixed
Method
toFixed()
returns a string, with the number written with a specified number of decimals:let x = 9.656; x.toFixed(0); // returns 10 x.toFixed(2); // returns 9.66 x.toFixed(4); // returns 9.6560 x.toFixed(6); // returns 9.656000
toPrecision
Method
toPrecision()
returns a string, with a number written with a specified length:let x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2); // returns 9.7 x.toPrecision(4); // returns 9.656 x.toPrecision(6); // returns 9.65600
valueOf
Method
valueOf()
returns a number as a number:let x = 123; x.valueOf(); // returns 123 from variable x (123).valueOf(); // returns 123 from literal 123 (100 + 23).valueOf(); // returns 123 from expression 100 + 23
In JavaScript, a number can be a primitive value (
typeof
= number
) or an object (typeof
= object
).The
valueOf
method is used internally in JavaScript to convert Number objects to primitive values.There is no reason to use it in your code.
Number
Method
Number(true); // returns 1 Number(false); // returns 0 Number("10"); // returns 10 Number(" 10"); // returns 10 Number("10 "); // returns 10 Number(" 10 "); // returns 10 Number("10.33"); // returns 10.33 Number("10,33"); // returns NaN Number("10 33"); // returns NaN Number("John"); // returns NaN
Previous Section
6.5 String MethodsCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.