While reading the book, Learning jQuery, I came across a Javascript method that I had never heard of. The .toFixed() method, which can only be called on numeric values, will return a string representation of the number with the given number of decimal places. For example, if you wanted to return a dollar formatted version of a number, you could call something like this:
Launch code in new window » Download code as text file »
This would take the number 15 and return the string, "15.00", to which we would prepped the dollar sign.
This is a function that I wish I had known about a long time ago. Formatting numbers has always been somewhat of a hassle in Javascript, especially after coming from ColdFusion where formatting numbers is an all-to-easy task. To see how this method works in detail, I decided to run a few tests on it:
Launch code in new window » Download code as text file »
While I know that it won't work on a String value, I ran a test on the string value of the number. This was just to see if Javascript would perform any kind of implicit data type conversion for us. Running this code, we get the following output:
String value did not work
1235
1234.6
1234.57
1234.568
1234.5679
1234.56789
1234.567890
1234.5678900
1234.56789000
1234.567890000
As you can see, it only works on numeric values. Also, you will notice that it rounds to the given decimal place (or to the closest integer if given "0" as the number of digits to display).
Very cool stuff; this will be a good tool to have in the Javascript tool belt.
Download Code Snippet ZIP File
Comments (8) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page
Great find, Ben! I've always been frustrated with trying to format numbers in JavaScript, too.
Posted by Ryan Stille on Oct 29, 2007 at 9:10 AM
There are several ways to convert strings to numbers in JavaScript. One way is the parseFloat that you've shown here, but you can convert it directly into a number with the following:
var str = Number('1234.56789');
An alternate method of moving a string to number is to subtract 0 from it:
var str = '1234.56789' - 0;
alert(str.toFixed(2)); // assuming that the string is actually a number
Not that it's much, but it is a tiny bit faster than parseFloat, at least on my system, but the differences don't show up until you're well above 10,000 iterations. At 100,000 iterations it's approximately 265 milliseconds for minus zero to 469 milliseconds for the parseFloat method, so for most cases it's better to with the more readable parseFloat.
FWIW: try-catch is fairly expensive, it would probably be better to test a variable for the existence of the toFixed method than to use a exception:
var StringValue = '1234.56789';
if(StringValue.toFixed && typeof StringValue.toFixed === 'funciton'){
// write to page
}
else{
// something did not work
}
Also, you're assuming that the value that is in NumericValue is actually a number after calling parseFloat, but parseFloat will return NaN (Not a Number) if the string can't be converted into a float, so you should either have done a RegExp match on your string to make sure it is a number that you can work with, or check for NaN before you do any other processing that relies on the value being a number. For example:
var StringValue = 'This is no longer a number 1234.56789';
var NumericValue = parseFloat(StringValue);
if( !isNaN(NumericValue) ){
// do your loop
}
else{
// something went wrong
}
anyway, just had a moment so I rambled, hope you don't mind. :-)
Posted by Danilo Celic on Oct 29, 2007 at 9:56 AM
@Danilo,
Thank you for the most excellent feedback. Very good suggestions here. I like the idea of using the Numeric() object constructor for creating numbers. I wonder, does it return NaN if you pass in a non-numeric value? I can test that on my, I was just thinking away...
Posted by Ben Nadel on Oct 29, 2007 at 6:20 PM
@Ben,
Yes, Number(str) will be NaN if the value of str isn't converted into a number. Make sure that you use isNan() to check for values being NaN because NaN does not equal NaN.
var str = 's1234.56789';
var n1 = Number(str);
var n2 = Number(str);
alert(n1 == n2);
This alerts false even though n1 and n2 look like they might be equal, but because they are NaN they aren't.
Posted by Danilo Celic on Oct 29, 2007 at 7:01 PM
In addition to the number-conversion methods already discussed here so far, you can also use the unary plus operator, e.g. +'10'. This is nice and cheap (performance-wise) and only adds one character.
As for toFixed(), you can save one character by using a space after a numeric literal, e.g. 10 .toFixed(2). If your numeric literal includes a decimal place you can even drop the space, e.g. 10.0.toFixed(2).
Posted by Steven Levithan on Oct 29, 2007 at 10:17 PM
I tried to perform a rounding operation - however for numbers have the decimal point position > 14 (i.e. 13 digits exist before the decimal place) the rounding is incorrect. Is it because the number goes out of range for 'integer' in javascript? For instance, the above method fails for the number
12345678912345.123456
Posted by Gayatri on Nov 29, 2007 at 2:26 AM
@Gayatri,
While I cannot say one way or the other, what you are suggesting sounds correct. That's a huge number! What are you doing? Calculating the number of bacteria in a culture or something (I sure hope you aren't working with dollars or that would just make me feel sad and insignificant :)).
Posted by Ben Nadel on Nov 29, 2007 at 7:13 AM
That was really helpful, wanted you to know, thanks :)
Posted by antiphobe on May 15, 2008 at 2:44 PM