JavaScript - String Format in Javascript - Asked By Shailendrasinh Parmar on 28-Jan-10 03:50 AM

Hello Friens,

I am using following function to get the string format as "2.30"

 String.format("%2.2f", 2.3);

The above function is given on few sites when I search for javascript string format. But it is not working. Can anybody suggest me why its not working or is there any other way to get the formatted string in javascript?

Thanks in advance.

String Format in Javascript - mv ark replied to Shailendrasinh Parmar on 28-Jan-10 04:12 AM

The JavaScript String object doesn't support any method called format()

To see the complete list of properties & methods of the String object, check this -
http://www.w3schools.com/jsref/jsref_obj_string.asp

It could be possible that method you are referring could be part of some custom JavaScript library.

re - Santhosh N replied to Shailendrasinh Parmar on 28-Jan-10 04:13 AM

As far as I know there is no string.format in javascript but you could actually add that function to your string variable and that might have confused you as described here

http://frogsbrain.blogspot.com/2007/04/javascript-stringformat-method.html

But, otherwise you could take that approach to format or use regular expressions as suggested here as well

http://www.geekdaily.net/2007/06/21/cs-stringformat-for-javascript/

Re :: String Format in Javascript - Shailendrasinh Parmar replied to Shailendrasinh Parmar on 28-Jan-10 05:07 AM

Thank you guys,

But I have done it using toFixed(number) function. It is the inbuilt function in javascript.

So,

 var num = 10;
var value = num.toFixed(num);

Here you will get value as 10.00

Thank you all.