Here's a function I wrote a while back...
Code:
// @param d String. Required.
// @param zeros Mixed. Optional.
// @param trun Boolean. Optional.
function parseDecimal(d, zeros, trunc) {
d=d.replace(/[^\d\.]/g,"");
while (d.indexOf(".") != d.lastIndexOf("."))
d=d.replace(/\./,"");
if (typeof zeros == 'undefined' || zeros == "") {
return parseFloat(d);
}
else {
var mult = Math.pow(10,zeros);
if (typeof trunc == 'undefined' || (trunc) == false)
return parseFloat(Math.round(d*mult)/mult);
else
return parseFloat(Math.floor(d*mult)/mult);
}
}
And a test page to see how it works...
Code:
<html>
<head>
<title>parseDecimal</title>
<script>
function parseDecimal(d, zeros, trunc) {
d=d.replace(/[^\d\.]/g,"");
while (d.indexOf(".") != d.lastIndexOf("."))
d=d.replace(/\./,"");
if (typeof zeros == 'undefined' || zeros == "") {
return parseFloat(d);
}
else {
var mult = Math.pow(10,zeros);
if (typeof trunc == 'undefined' || (trunc) == false)
return parseFloat(Math.round(d*mult)/mult);
else
return parseFloat(Math.floor(d*mult)/mult);
}
}
</script>
</head>
<body>
<form>
Take <input type="text" name="source"> and
<select name="format">
<option>round to</option>
<option>truncate at</option>
</select>
<select name="places">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
decimal places<br>
<input type="button" value="parseDecimal" onClick="this.form.output.value = parseDecimal(this.form.source.value, this.form.places.selectedIndex+1, this.form.format.selectedIndex)"> including optional parameters<br>
<input type="button" value="parseDecimal" onClick="this.form.output.value = parseDecimal(this.form.source.value)"> excluding optional parameters<br>
<input type="button" value="parseFloat" onClick="this.form.output.value = parseFloat(this.form.source.value)"> for comparison<br>
<input type="button" value="parseInt" onClick="this.form.output.value = parseInt(this.form.source.value)"> for comparison<br>
<input type="text" readonly="true" name="output">
</form>
</table>
</body>
</html>
Bookmarks