This is a discussion on How do I convert a Number into a String with exactly 2 decimal places? within the HTML, CSS and Javascript Coding Techniques forums, part of the Web Development category; Hi all...... How do I convert a Number into a String with exactly 2 decimal places? Thanks & Regards itbarota....
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi... When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. N = Math.round(N*100)/100 only converts N to a Number of value close to a multiple of 0.01; but document.write(N) does not give trailing zeroes. ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5) introduced N.toFixed, the main problem with this is the bugs in JScripts implementation. Most implementations fail with certain numbers, for example 0.07. The following works successfully for M>0, N>0: function Stretch(Q, L, c) { var S = Q if (c.length>0) while (S.length<L) { S = c+S } return S } function StrU(X, M, N) { // X>=0.0 var T, S=new String(Math.round(X*Number("1e"+N))) if (S.search && S.search(/\D/)!=-1) { return ''+X } with (new String(Stretch(S, M+N, '0'))) return substring(0, T=(length-N)) + '.' + substring(T) } function Sign(X) { return X<0 ? '-' : ''; } function StrS(X, M, N) { return Sign(X)+StrU(Math.abs(X), M, N) } Number.prototype.toFixed= new Function('n','return StrS(this,1,n)') i hope this will help you.... thnx... |
| |||
| a = (32767).toString(16) // this gives "7fff" b = (255).toString(8) // this gives "377" c = (1295).toString(36) // this gives "zz" d = (127).toString(2) // this gives "1111111" function toRadix(N,radix) { var HexN="", Q=Math.floor(Math.abs(N)), R; while (true) { R=Q%radix; HexN = "0123456789abcdefghijklmnopqrstuvwxyz".charAt(R)+H exN; Q=(Q-R)/radix; if (Q==0) break; } return ((N<0) ? "-"+HexN : HexN); } |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Convert Number to rupees in Words using JavaScript | poornima | HTML, CSS and Javascript Coding Techniques | 2 | 12-31-2007 01:25 AM |
| How can I convert a number to a different base (radix)? | kingmaker | HTML, CSS and Javascript Coding Techniques | 1 | 08-10-2007 04:44 AM |
| Decimal to any number system | kbala | Adobe Flex Programming | 3 | 07-30-2007 01:49 AM |
| How to convert Decimal to Binary in Flash? | kingmaker | Flash Actionscript Programming | 1 | 07-21-2007 02:48 AM |
| How would you replace a char in string and how do you store the number of replacement | vadivelanvaidyanathan | Perl | 1 | 07-17-2007 04:34 AM |