JavaScript Number valueOf() Method
-
Syntax of JavaScript Number
valueOf()
Method -
Example 1: Use the
number.valueOf()
Method to Get the Actual Value ofNumber
Object -
Example 2: Use the Actual Value of the
Number
Object as an HTML Text
In JavaScript, the number.valueOf()
method is useful to get the primitive value of the Number
object.
We can create the Number
object using the number value, and the primitive value of the Number
object means the value using which we have created the object. Also, the primitive value of the Number
object can be changed when we assign a new value to the Number
object.
Syntax of JavaScript Number valueOf()
Method
let number_object = new Number(1000);
number_object.valueOf();
Parameters
This method doesn’t contain any parameters.
Return
The number.valueOf
method returns the actual value of the Number
object.
Example 1: Use the number.valueOf()
Method to Get the Actual Value of Number
Object
We have created four different Number
objects in the example below. Printing the Number
object will only print the object
text rather than its actual value.
To print the actual values, we have to use the number.valueOf()
method.
We have created the num_object4
using the exponential notation of the number. In the output, users can see that exponential notation from num_object4
is removed by the valueOf()
method, showing the proper number value.
let num_object1 = new Number(2302);
let num_object2 = new Number(-452);
let num_object3 = new Number(0.4621);
let num_object4 = new Number(4342.312e+10);
console.log(num_object1.valueOf());
console.log(num_object2.valueOf());
console.log(num_object3.valueOf());
console.log(num_object4.valueOf());
Output:
2302
-452
0.4621
43423120000000
Example 2: Use the Actual Value of the Number
Object as an HTML Text
When users want to use the Number
object value as an HTML text, they can’t use the Number
object directly. We have to use the number.valueOf()
method.
In the example below, we have created the <p>
tag and accessed it using the id inside JavaScript. After that, we changed its text using the innerHTML
property and added the actual value of the Number
object.
<html>
<body>
<p>The actual value of the number object is</p>
<p id="text"></p>
</body>
<script>
let text = document.getElementById('text');
let num_object1 = new Number(45212);
text.innerHTML = num_object1.valueOf();
</script>
</html>
Output:
The actual value of the number object is
45212
The number.valueOf()
method is compatible with all modern browsers, and users can use the value of the Number
object.