Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - ToPrecision

toPrecision() returns a string, with a number written with a specified length including the integers and decimals (excluding the decimal itself) - uses rounding.

toPrecision(5) = "123.45" - the length of the string

toPrecision() or toPrecision(0) returns the whole thing - unaltered.


let x = 9.56475322;
let output = "";
output += x.toPrecision(0) + "<br />";
output += x.toPrecision(2) + "<br />";
output += x.toPrecision(4) + "<br />"; // <-- rounding!
                                                 output +=x.toPrecision(6) + "<br />" ;
                                                 let demo1=document.getElementById("demo1");
                                                 demo1.innerHTML=output;