|
Q1684 How can I round to two decimal places, but without losing any zeros in the answer?
irt.org | Knowledge Base | JavaScript | Number | Q1684 [ previous next ]
Q1684 How can I round to two decimal places, but without losing any zeros in the answer?
Try:
<script language="JavaScript"><!--
function toDollarsAndCents(n) {
var s = "" + Math.round(n * 100) / 100
var i = s.indexOf('.')
if (i < 0) return s + ".00"
var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
if (i + 2 == s.length) t += "0"
return t
}
document.write(toDollarsAndCents(1) + '<br>');
document.write(toDollarsAndCents('1.') + '<br>');
document.write(toDollarsAndCents(1.0) + '<br>');
document.write(toDollarsAndCents(1.1) + '<br>');
document.write(toDollarsAndCents(1.10) + '<br>');
document.write(toDollarsAndCents(1.11) + '<br>');
document.write(toDollarsAndCents(1.110) + '<br>');
//--></script>
|
|
|
Copyright © 1996-2009 irt.org, All Rights Reserved.