Zack Lovatt | 2d Technical Director

I focus on toolkitting, building custom studio pipelines, expression rigging projects, and creating data-driven animation workflows.

Mail GitHub LinkedIn Skype Vimeo
March 5, 2012

toFixed() – Limiting decimal points

Posted In: expressions

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.

// value is [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–

// value is [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!

Tagged:
0 Comments

Would you like to share your thoughts?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.