JS: Number.prototype.toFixed

By Xah Lee. Date: . Last updated: .

number.toFixed(n)

Return a string representation of number, with n digits after decimal, padded by 0 if necessary.

The number may be rounded up.

// truncate number

console.log(
 3.12345.toFixed(0) === "3" ); // true

console.log(
 3.12345.toFixed(1) === "3.1" ); // true

console.log(
 (3.1).toFixed(3) === "3.100" ); // true

// the arg to toFixed cannot be negative. Else, RangeError

Rounded up example.

// toFixed may round up
console.log ( (3.56).toFixed ( 0 ) === "4" ); // true
console.log ( (3.56).toFixed ( 1 ) === "3.6" ); // true

[see JS: Format Number]

Reference

ECMAScript® 2016 Language Specification#sec-number.prototype.tofixed

Number Topic

  1. JS: Format Number
  2. JS: String to Number
  3. JS: Number Object
  4. JS: Number Constructor
  5. JS: Number.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog