How to convert number in specific precision in Javascript

Description

The toPrecision() method returns either the fixed or the exponential representation of a number. This method takes the total number of digits to represent the number as the argument.

Example


var num = 99; 
console.log(num.toPrecision(1)); //"1e+2" 
console.log(num.toPrecision(2)); //"99" 
console.log(num.toPrecision(3)); //"99.0" 
/* ww  w  .j  av a  2  s  .c o m*/

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window