Evertjan. wrote:
Max Merten wrote on 14 mrt 2005 in comp.lang.javascript:
ich habe Probleme mit der Berechnung von Preisen:
bisherigerVKP = document.form.bisherigerVKP.value; Bspw: 200,20
bisherigerEKP = document.form.bisherigerEKP.value; Bspw: 188,40
neuerVKP = document.form.neuerVKP.value; Bspw: 250,00
neuerEKP = document.form.neuerEKP.value; Bspw: 200,00
zumeldenderVKP = neuerVKP - bisherigerVKP;
zumeldenderEKP = neuerEKP - bisherigerEKP;
function c2p(x) {
return x.replace(/,/,'.')
The modified value should be checked to ensure it's a number
before putting it back in the page.
x = x.replace(/,/,'.');
// Test x is digits with two digits after the decimal point
return /^\d+\.\d\d$/.test(x))? x :
n + '\nNummer nein gut';
}
zumeldenderVKP = c2p(neuerVKP) - c2p(bisherigerVKP)
Excuse my reply in English, I haven't tried Deutsch since
school...
IIRC, Deutchlanders like to write numbers: 23.234.234,00
where the English (Roman?) numbering system would have written:
23,234,234.00.
The following script attempts to remove thousands separators and
ensure the decimal point is a '.' and not a ','. It looks to
see if a '.' comes before a ','. If so, it removes all '.' and
changes the ',' to a '.'.
If a comma comes before a period, it just removes the commas.
Lastly, it tests to see if the final number is only digits
followed by a '.' and one or more digits.
There should also be an on-screen tip that suggests the
appropriate format (as indicated in the HTML).
It is impossible to be exhaustive when validating this way
unless you only allow one format or the other. If there is only
one '.' or one ',' it's impossible to test if it's a decimal
point with three places or a thousands separator.
<script type="text/javascript">
function doIt(n){
var x = n;
if (x.lastIndexOf('.') < x.lastIndexOf(',')){
x = x.replace(/\./g,'').replace(/,/,'.');
} else {
x = x.replace(/,/g,'');
}
// Check it's a reasonable number
return (/^\d+\.\d+$/.test(x))? x :
n + '\nInput not acceptable';
}
</script>
<label for="numberSlot">Please enter a value
(e.g. 23.000,00)<br>
<input type="text" width="50" id="numberSlot" onblur="
document.getElementById('result').innerHTML=
doIt(this.value);">
</label><br>
<span id="result"></span>
--
Rob