How to format to 2 decimal places in javacript?

# Thread: How to format to 2 decimal places in javacript?

1. Member
Join Date
Dec 1969
Posts
51

## How to format to 2 decimal places in javacript?

How can I format a number to display 2 decimal places in javacript? let say I subtracted a number w/ a decimal from a decimal number, the result should be in 2 decimal places.

2. Senior Member
Join Date
Dec 1969
Posts
2,334

## RE: here is a JS function to do that...

&#060;script language="javascript"&#062;<BR><BR>function FormatNumber ( AnyNumber ) <BR>{ <BR> <BR> var FormattedNumber = "" + ( AnyNumber + 0.00500000001 ); <BR><BR> <BR> var nPos = FormattedNumber.indexOf ( &#039;.&#039; ); <BR><BR> if ( nPos &#060; 0 ) <BR> { <BR> FormattedNumber += &#039;.00&#039;; <BR> } <BR> else <BR> { <BR> FormattedNumber = FormattedNumber.slice ( 0, nPos + 3 ); <BR> <BR> var nZero = 3 - ( FormattedNumber.length - nPos ); <BR><BR> for ( var i=0; i&#060;nZero; i++ ) <BR> FormattedNumber += &#039;0&#039;; <BR> } <BR><BR> return FormattedNumber; <BR>} <BR><BR><BR>&#060;/script&#062;

3. Member
Join Date
Dec 1969
Posts
51

## thanks! how about in vbscript?

:)

4. Senior Member
Join Date
Dec 1969
Posts
2,334

## RE: are you trying to...

test my skills in JavaScript and VBScript:)<BR><BR>You can use FormatNumber function of VBScript for your purpose.

5. Senior Member
Join Date
Dec 1969
Posts
96,118

## Seems way too complex...

...and doesn&#039;t handle negative numbers.<BR><BR>How about:<BR><BR>function FormatTwo( num )<BR>{<BR> var sign = "";<BR> if ( num &#060; 0 )<BR> {<BR> sign = "-";<BR> num = -num;<BR> }<BR> num = Math.round( num * 100 );<BR> if ( num &#060; 10 ) return sign + "0.0" + num;<BR> if ( num &#060; 100 ) return sign + "0." + num;<BR> // convert to string now...<BR> num = sign + num;<BR> return num.substring(0,num.length-2) + "." + num.substring(num.length-2);<BR>}<BR>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•