In most applications using the
Round method of the
Decimal class will work fine.
Other times you may want more control over the final number. This script shows how to get a
decimal's remainder which allows you to perform your own rounding, rather than rounding toward the nearest number.
<%@ Page Language="C#" %>
<script runat="server">
public void Page_Load(Object sender, EventArgs e){
//setup the main decimal number
Decimal mydeci = new Decimal(2.6);
//get the remainder
Decimal remainder = Decimal.Remainder(mydeci,Decimal.Floor(mydeci));
//convert to integer
int mydeciint = System.Convert.ToInt32(Decimal.Floor(mydeci));
//setup the number to check the remainder against
Decimal checknum = new Decimal(0.7);
Response.Write(mydeciint + "<br>");
Response.Write(remainder + "<br>");
//if reaminder is greater than checknum
if(remainder >= checknum){
mydeciint = mydeciint + 1;
}else{
}
Response.Write(mydeciint + "<br>");
}
</script>
|
The Remainder method of the Decimal class computes the remainder after dividing two decimal values. So in
order to get the remainder of our number 2.6 we divide the original decimal by the number to the right of the
decimal. We get that number by using the method Floor which rounds a decimal to the closest integer towards negative
infinity, which will always get the lowest value (in our case it is 2). Once we have that information we can just
use that within the Remainder method to get our decimal's remainder (which will be 2.6/2).
We can then perform our own rounding and do things a little differently. In our script, we are only rounding a number up if the
number to the left of the decimal point is greater or equal to 7, rather than 5 (which is the default for Round).