JavaScript Number method: toPrecision()
[this page | pdf | back links]
The toPrecision() method (when applied to JavaScript
numbers) returns
a string representing the number with a fixed number of significant digits.
It
has the following syntax with the following parameters:
number.toPrecision(n)
Parameter
|
Required / Optional
|
Description
|
n
|
Optional
|
(default is 0), Integer indicating number of
digits. If omitted then returns a string representation of the entire number
(without any formatting)
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>
<script>
var a = 123.48;
document.getElementById("Example").innerHTML =
'var a = ' + a + ';<br>' +
'var x = a.toPrecision(1);';
document.getElementById("Result").innerHTML = a.toPrecision(1);
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodNumberToPrecision() {
var z = 12.5; return !!z.toPrecision;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript Numbers and Math