PDA

View Full Version : Only two digits after decimal


ksridhar69
10-21-2002, 04:26 PM
User wants to enter only two digits after decimal. If they enter more than 2 digits just alert

beetle
10-21-2002, 04:50 PM
Shooting from the hip....function checkDecimal(val) {
if (val.length >= 3)
if (/\d*\.\d\d$/.test(val))
return true;
else {
alert("Only two decimal places allowed");
return false;
}
}

<input type="text" name="decimal" onKeyPress="return checkDecimal(this.value)">

jkd
10-21-2002, 06:03 PM
I have this code snippet on my hard drive I wrote some time ago, and I'm assuming it works:

// Number.prototype.toFixed() fix for older browsers
if (typeof Number.prototype.toFixed == 'undefined') {
Number.prototype.toFixed = function(digits) {
if (digits == 0)
return Math.round(this);
var m = Math.pow(10, digits);
var result = (Math.round(this * m) / m).toString();
if (result.indexOf('.') == -1)
result += '.0';
var dec;

while (result.split('.')[1].length < digits)
result += '0';

return result;
}
}


It is a fix for older browsers that don't natively support the toFixed() method of Number.

You use it like:

1234.4543221.toFixed(2)
// "1234.45"

epack
10-21-2002, 07:17 PM
This also works, but it's a rounding thing rather than a truncation per se:

document.someform.somefield.value = Math.round(anotherfield*100)/100;

elaine