Formatting Numbers with the JavaScript toFixed()* Method [Examples]

JavaScript toFixed()

This tutorial will show you how to format numbers to a fixed number of decimal places in the JavaScript programming language.

JavaScript Number Variables

JavaScript variables have different types. The type of a variable defines what kinds of values it can hold, and what can be done with that value.

Number typed variables hold numeric values and include a number of methods (built in functions) for performing numeric operations.

Number variables are declared by simply assigning a numeric value to a variable, or using the Number constructor.

var myNumber = 46;

or

var myNumber = Number(46);

Once a variable of the Number type has been declared with a numerical value, the toFixed() method is available to format it to a specified number of decimal places.

JavaScript Number.toFixed() Method Syntax

The toFixed() method will format a number to a fixed number of decimal places/digits. Here’s the Syntax:

number.toFixed(digits)

Note that:

  • toFixed() does NOT modify the original number value/variable it is called from
  • STRING containing the formatted number is returned!
  • digits is an optional parameter
    • If it is not provided, a default value of 0 will be used
  • The number will be rounded if necessary
    • Zeros will be appended if necessary to reach the required number of decimal places

toFixed() Method Code Examples

let myNumber = 12345.6789

myNumber.toFixed()       // Returns '12346': Note rounding to nearest integer as default number of decimal places is 0
myNumber.toFixed(1)      // Returns '12345.7': Note number is rounded
myNumber.toFixed(6)      // Returns '12345.678900': Note zeros added to the end to reach number of desired decimal places
(1.23e+20).toFixed(2)  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2)  // Returns '0.00'
2.34.toFixed(1)        // Returns '2.3'
2.35.toFixed(1)        // Returns '2.4': Note number rounded up
2.55.toFixed(1)        // Returns '2.5': Note number rounded down
-2.34.toFixed(1)       // Returns -2.3 : Note that due to operator precedence, a string is not returned as the '-' operator has coerced the value back to a number
(-2.34).toFixed(1)     // Returns '-2.3': Note, above situation avoided as '-' operator is bracketed

Floating Point Numbers Warning

It’s also worth keeping in mind that floating point numbers are not always accurately represented by computers – check out our article on why this is and how to avoid running into the commonly associated problems.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published.