Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Moose

Moose Avatar

****
Senior Member

449


August 2005
toFixed() and toPrecision() Methods

In this tutorial, I am going to discuss two very overlooked methods yet well supported number methods that can be handy when doing math in JavaScript. Now, basically they are used to format the number you have to a certain amount of overall places. Both work in IE 5+ and FF 1.5. They most likely work in other popular browsers as well. :)

Now for toFixed(). It accepts one parameter which is the number of decimal places you want your script to go out to. Notice if the decimal place after it is larger than 5, it will round up. Also, if you use a number larger than the amount of decimal places you have, the method will add decimal places to compensate for the extra decimal places.

Syntax:

number.toFixed(number of decimal places);



<script type="text/javascript">
<!--
var newnum = 50.688;
newnum = newnum.toFixed(1);
alert(newnum);
//-->
</script>


Result:
50.7

So first we declare newnum as a variable that holds a number. We then change the contents of it using the toFixed() method.

Let’s say we did something a bit different:

newnum = newnum.toFixed(4);

That would simply add an extra 0 so we would have 4 decimal places and our result would be:

50.6880

That pretty much covers toFixed().

Now for toPrecision(). This changes the amount of places in the entire number not just the decimal places. It’s great for something like significant figures. Let’s try our old script from before except with toPrecision().

Syntax:

number.toPrecision(number of place holders)



<script type="text/javascript">
<!--
var newnum = 50.688;
newnum = newnum.toPrecision(3);
alert(newnum);
//-->
</script>


That bit above does the same thing newnum.toFixed(1) would except for different reasons. It returns the number to three places and the last place is rounded up because the placeholder before it was greater than 5.

It should return:

50.7

We can add decimal places as well by increasing our parameter past the number of place holders it has. If you use a parmeter smaller than the amount of whole number places you have, it will be return in scientific notation. Enjoy, I find them quite handy. :)

Greg says:
Coding music...
Greg says:
Hmm...
Greg says:
I wouldn't rule it out. :P
Chris 3.0 [New features? Yes.] says:
:P
Greg says:
If you think about machine code it's a bunch of 1s and 0s
Chris 3.0 [New features? Yes.] says:
Anything is possible.
Greg says:
Yeah try to code Metallica
Chris 3.0 [New features? Yes.] says:
:P Yeah, I'll get right on that... right after I learn to fly.

Chris

Chris Avatar

******
Head Coder

19,519


June 2005
You or CJ mentioned them to me before, but I've never looked into them. Looks fun. :D I'll need to find a use for them in JavaScript (I can think of something....), but they should be helpful none the less. :)

newBookmarkLockedFalling