Forum Moderators: open
benj if you're asking what I **think** you're asking - how to get a two-digit (monetary) decimal part from every calculation regardless of whether it's fractional or not - the only consistent solution I've found (which may not add up to much! :-) )is to pick apart the number as a string and reassemble it. This may not be the best way, but it works:
<form>
<input type="text" size="12" name="decimal" value="">
<input type="button"onClick="calcDecimal(this.form);" value="Calculate Monetary">
</form>
<script language="Javascript">
// This can be any function that does your math. Each time
// you want a monetary format, pass the number to
// truncate, it will return xx.xx
function calcDecimal(form) {
if (isNaN(form.decimal.value)) { alert('Come on, it has to be a number!'); return; }
var monetary = truncate(form.decimal.value);
alert(monetary);
}
function truncate(num) {
var str = num + ''; // Now it's a string.
if (str.indexOf('.') == -1) { return str + '.00'; }
dot = str.length - str.indexOf('.');
if (dot > 3) { return str.substring(0,str.length-dot+3); }
else if (dot == 2) { return str + '0'; }
return str;
}
</script>
<script type='text/javascript'>
function ExactRound(a,b,e){
a=String(a)
b=String(b)
var deci=( a.split('\.')[1].length > b.split('\.')[1].length )?a.split('\.')[1].length:b.split('\.')[1].length;
var c= Number(a) + Number(b);
var expo= (Math.pow(10,deci))
var result=((Math.round(c*expo)/expo).toFixed(e));
return result;
}
</script></head>
<body>
<script type='text/javascript'>
alert(ExactRound(70.8021,86.104,4))
</script>
</body>
</html>
Am I to take it, rocknbill, that the toFixed() method of the Number object doesn't work for you? Are you coding for older browsers?
I should also note that there are those who feel multiplying or dividing a string by 1 is a more efficient way to convert the string to a number, as compared with using the Parse methods. That argument is not without some shred of merit, so I find the best policy is to simply ignore it (ignorance is the best tool there is for for avoiding confusion).
Didn't mean to jack the thread but that's actually the reason I originally asked.