toPrecision (JavaScript)

Gets a string representation of a number using exponential (scientific) or fixed-point notation.

Defined in

Number (Standard - JavaScript)

Syntax

toPrecision() : string

toPrecision(precision:int) : string
Parameters Description
precision The number of decimal places in the fractional part of the notation. Defaults to 0.
Return value Description
string The string value of the number in exponential or fixed-point notation.

Usage

The number is represented in fixed-point format if it can be, and exponential format otherwise.

Examples

This example prints a number in fixed-point format with various precisions.
function p(stuff) {
 	print("<<<" + stuff + ">>>");
}

var n : Number;

try {
	n = new Number(543.21);
	p(n.toPrecision(0)); // Prints <<<543>>>
	p(n.toPrecision(1)); // Prints <<<543.2>>>
	p(n.toPrecision(2)); // Prints <<<543.21>>>
	p(n.toPrecision(3)); // Prints <<<543.210>>>
	p(n.toPrecision(4)); // Prints <<<543.2100>>>
	
} catch(e) {
	p("Error = " + e);
}

This example prints a number in exponential format with various precisions.

function p(stuff) {
 	print("<<<" + stuff + ">>>");
}

var n : Number;

try {
	n = new Number(54321E-99);
	p(n.toPrecision(0)); // Prints <<<5E-95>>>
	p(n.toPrecision(1)); // Prints <<<5.4E-95>>>
	p(n.toPrecision(2)); // Prints <<<5.43E-95>>>
	p(n.toPrecision(3)); // Prints <<<5.432E-95>>>
	p(n.toPrecision(4)); // Prints <<<5.4321E-95>>>
	
} catch(e) {
	p("Error = " + e);
}

This example prints a number in exponential format with various precisions.

function p(stuff) {
 	print("<<<" + stuff + ">>>");
}

var n : Number;

try {
	n = new Number(54321E99);
	p(n.toPrecision(0)); // Prints <<<5E103>>>
	p(n.toPrecision(1)); // Prints <<<5.4E103>>>
	p(n.toPrecision(2)); // Prints <<<5.43E103>>>
	p(n.toPrecision(3)); // Prints <<<5.432E103>>>
	p(n.toPrecision(4)); // Prints <<<5.4321E103>>>
	
} catch(e) {
	p("Error = " + e);
}