SitePoint Sponsor

# Thread: Truncating a Decimal

1. ## Truncating a Decimal

Hey, I'm coding a script that needs to truncate a variable after the hundredths place. In other words...I want to go from 1.5839 to 1.58, from 84.5375 to 84.53, etc.

Just drop everything after the hundredths place (second digit after the decimal point).

Thanks in advance!

2. I just decided to multiply by 100, round, then divide by 100 for lack of a real method.

3. Code:
```val = 1.5839
Response.Write FormatNumber(val,2)```

4. 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>```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•