Her er et bud mere.
Demoen kører med 2 decimaler, hvis der er decimaler, og indeholder en alternativ rutine, hvis der skal køres med dansk format.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "
http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>Number format </title>
<style type="text/css">
body {
font-family: sans-serif;
}
.numberDiv {
border: 2px solid gold;
padding: 20px;
background-color: LemonChiffon ;
display: table-cell;
width: 300px;
text-align: center;
}
.cell {
display: table-cell;
padding: 20px;
width: 300px;
text-align: right;
}
</style>
<script type="text/javascript">
function AddToDiv(id, value) {
var no = parseFloat( document.getElementById(id).firstChild.nodeValue.replace(/,/g,'') );
no += value;
document.getElementById(id).firstChild.nodeValue = FormatNumber(no, ',', '.') ;
}
function AddToDivDK(id, value) {
var no = parseFloat( document.getElementById(id).firstChild.nodeValue.replace(/\./g,'').replace(',','.') );
no += value;
document.getElementById(id).firstChild.nodeValue = FormatNumber(no, '.', ',') ;
}
function FormatNumber(no, Tsep, Dsep) {
parts = no.toString().split('.');
return AddCommas(parts[0], Tsep) + (parts.length > 1 ? (Dsep + parseFloat('.' + parts[1]).toFixed(2).split('.')[1] ) : '');
}
function AddCommas(no, Tsep) {
if (no.length > 3) {
return AddCommas(no.substr(0, no.length - 3), Tsep ) + Tsep + no.substr(no.length - 3);
}
return no;
}
</script>
</head>
<body>
<p>
<div class="cell">
<input type="button" value="Add To Number" onclick="AddToDiv('numberDiv1', 123456789)">
</div>
<div id="numberDiv1" class="numberDiv">
123,456,789
</div>
</p>
<p>
<div class="cell">
<input type="button" value="Add To Number (2 decimals)" onclick="AddToDiv('numberDiv2', 123456789.87)">
</div>
<div id="numberDiv2" class="numberDiv">
123,456,789.87
</div>
</p>
<p>
<div class="cell">
<input type="button" value="Læg til heltal" onclick="AddToDivDK('numberDiv3', 123456789)">
</div>
<div id="numberDiv3" class="numberDiv">
123.456.789
</div>
</p>
<p>
<div class="cell">
<input type="button" value="Læg til decimaltal" onclick="AddToDivDK('numberDiv4', 123456789.87)">
</div>
<div id="numberDiv4" class="numberDiv">
123.456.789,87
</div>
</p>
</body>
</html>