In today's thrilling post I'm going to cover how to limit the number of digits after a decimal while working with expressions. While I know of a few ways to go about doing this, I'm going to cover the toFixed() method.


(As an aside, another option is toPrecision() which limits the number of significant digits, but the practical applications of using it over toFixed() are few and far.)

So. Simply, toFixed() limits the number of digits to after its decimal point to x, by rounding up; let's take a look, using random. I'm going to give sample results, by the way, for the sake of showing examples.

random(1);

// Result: 0.66781947055548

We've got a really long number here, and that's damned unseemly. Let's say you were doing some interface work and needed a number to change every frame-- this probably wouldn't work. Too many digits! Don't worry-- that's where toFixed() comes in.

random(1).toFixed(3);

// Result: 0.668

See, now that we've added toFixed(), and told it to limit the result to 3 digits post-decimal, our result looks much, much cleaner.

This doesn't just work with random numbers, though! Pretty much any number can be shortened this way.

// if value == 967.337125645
value.toFixed(3);

// Result: 967.337

One last note is that toFixed() will also add trailing 0's when needed, too, to fill up the number specified--

// if value == 2345.1
value.toFixed(4);

// Result: 2345.1000

That's all I really wanted to go over for today-- if you've got any questions about this stuff, feel free to leave a comment / send an email!