FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? (2008-10-10)

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
-----------------------------------------------------------------------

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. See the section on "simple decimal arithmetic"
for Rounding issues.

` 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 ` Number.prototype.toFixed `, the main problem
with this is the bugs in JScript's 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 = String(Math.round(X * Number("1e" + N)));
if (S.search && S.search(/\D/) != -1) {
return '' + X;
}
with (String(Stretch(S, M+N, '0')))
return substring(0, T = (length-N)) + '.' + substring(T);
}

function Sign(X) {
return X > 0 ? "+" : X < 0 ? "-" : " ";
}

function StrS(X, M, N) {
return Sign(X) + StrU(Math.abs(X), M, N);
}

Number.prototype.toFixed = function(n){
return StrS(this,1,n);
};

http://www.merlyn.demon.co.uk/js-round.htm

http://msdn2.microsoft.com/en-us/library/sstyff0z.aspx


--
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://jibbering.com/faq/index.html.
The FAQ workers are a group of volunteers. The sendings of these
daily posts are proficiently hosted by http://www.pair.com.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,834
Latest member
BuyCannaLabsCBD

Latest Threads

Top