我写了这个简短的 html 和 javascript 代码。您可以在http://jsfiddle.net/a4Mz5/8/访问代码,但它似乎不起作用。我正在寻找单击提交时要填充的值。
<html>
<head> Simple page </head>
<body>
<form id="enrollment">
<input type="button" value="submit" onclick="updateCost();">
value = <input type="text" name="cost">
</form>
<script>
function updateCost(){
document.enrollment.cost.value = formatCurrency(0.9946153813);
}
function formatCurrency(num) {
if(isNaN(num)) return "$0.00";
// ACCOUNTING RULES: ROUND DOWN IF LAST DIGIT IS 5 AND SECOND TO LAST DIGIT IS EVEN
num = new String(parseFloat(num).toFixed(3));
if(num.charAt(num.length-1) == '5' && parseInt(num.charAt(num.length-2)) % 2 == 0) {
num = num.substring(0,num.length-1);
}
var cents = Math.abs(Math.round((num * 100) % 100));
if(cents < 10) {
cents = "0" + cents;
}
var n = ""; var count = 0; var neg = num < 0;
num = Math.floor(Math.abs(num)).toString();
for(var i = num.length - 1; i >= 0; i--) {
if(count > 0 && count % 3 == 0) n = "," + n;
n = num.charAt(i) + n;
count++;
}
return (neg ? "-" : "") + ("$" + n + "." + cents);
}
</script>
</body></html>