Posts Tagged ‘round’

Precision with Double Numbers in C#

A provided function of C# in the Math class is the function Round. The round function has two inputs. The first input field is of type double and the number requiring rounding. The second input type is of type int and indicates the precision of the first input field. This round function allows you to provide a degree of precision to your numbers.

public static double Round(double value, int digits)

A few important facts:

  1. When double value is rounded, if it is less than 5, it is rounded down. If it is equal to or greater than 5, the value is rounded up.
  2. Valid int digits are integer between 0 to 14.
  3. An int digit value of 0 will output a whole number.

Provided below is an working example:

double example = 12.34567;
double output = Math.Round(example, 3);

The value output in the above example equal 12.346.

Prevent Round Trip Database Access Across Page Loads

Round trip database reads becomes an issue with large databases. You may notice this occurs in grid views. Each time the dataset is sorted or filtered, the default grid view needs to be data binded. In most cases, the data source is the database (sql statement or stored procedure). An easy way to prevent these round trips across page loads is to use a session variable. One important aspect to note is that session variables expire by default after fifteen minutes.

We are going to store a Boolean variable rememberMe in a ViewState. By storing the Boolean in a ViewState, rememberMe will retain its value across page loads. In this example, the boolean variable rememberMe will default to false. The variable rememberMe can be read to and from as if any public class variable.

public partial class _Default : System.Web.UI.Page
{
  public bool rememberMe
  {
    get
    {
      object o = ViewState["rememberMe "];
      return (o == null)? false : (bool)o;
    }
    set
    {
      ViewState["rememberMe"] = value;
    }
  }

  protected void Page_Load(object sender, EventArgs e)
  {

  }

}

Again, it is important to note that session variables expire by default after fifteen minutes. If a default value is not assigned, additional logic is required to prevent unanticipated affects. This method is very effective when retrieving an extremely large number of records. You will immediately notice the first query will take the standard query time, but each subsequent action on the same dataset will be very quick.