Number Formating In Javascript

JavaScript provides Number.toFixed(n), Number.toPrecision(n) and Math.round(n) functions for number formatting.

Number.toFixed(n) – n = Number of decimal digits required. Formats number for ‘n’ number of decimal digits. Number is rounded up and ’0′s are added after decimal point if needed to create the desired decimal length.

var n = 685.5428;
var result;
result=n.toFixed(2); //returns 685.54
result=n.toFixed(5); //returns 685.54280 (padding)
result=n.toFixed(3); //returns 685.543 (round up)
n = 547;
result=n.toFixed(2); //returns 547.00

Number.toPrecision(n) – n = Number of significant digits required. Formats number so that it is of length ‘n’. A decimal point and ’0′s are used if needed to create the desired length.

var n = 398.456;
var result;
result=n.toPrecision(5); //returns 398.46 (round up)
result=n.toPrecision(7); //returns 398.4560 (padding)

Math.round(n) – n = number to be rounded. Number is rounded off to the nearest integer using the “.5″ up rule.

var result;
result=Math.round(14.67); //returns 15 (round up)
result=Math.round(14.47); //returns 14

Round number to ‘n’ decimal digits using Math.round
To round any number to n decimal points, perform following steps.
1 – Multiple the original number by 10^n i.e 10 to the power of n
2 – Apply Math.round() to the result
3 – Divide result by 10^n

var result;
result=Math.round(14.6789 * 100) /100;  //returns 14.68 (round to two decimals)
result=Math.round(14.6789 * 10) /10;   //returns 14.7 (round to 1 decimal)

Javascript slideshow (Rotating Image)

Hi All,

Today I am presenting slideshow using javascript. You can use this script statically as well as dynamically. I have mentioned slideshow both ways.

See below javascript.

<script language="JavaScript" type="text/javascript">
   var slideshowDelay = 1500;
   var tempImage = 0;
   var totalImages = 6;
   var slideshowImages = new Array();

   //Use below for loop for dynamic slideshow
   for (i = 0; i < totalImages; i++)
      slideshowImages[i] = new Image(480, 300);
      slideshowImages[i].src = 'Images/' + (i + 1) + '.jpg';

   function RotateImage()
      setTimeout("RotateImage()", slideshowDelay);

   function NextImage()
      //For static slideshow
      //document.getElementById("imgID").src = 'Images/' + (tempImage+1) + '.jpg';

      //For Dynamic slideshow
      document.getElementById("imgID").src = slideshowImages[tempImage].src;

      if (tempImage >= totalImages) tempImage = 0;

Here, I have put function RotateImage. Call this function on body load like,

<body onload="RotateImage()">
   <table border="0">
            <img src="Images/1.jpg" id="imgID" width="480" height="300" border="0" alt="Slideshow"    /><br />

Note: Put all your images in Images folder and name it like 1.jpg, 2.jpg…

Selecting a Comma Seperated List

Hello All,

Sometimes we required a comma separated value instead of table. So generally people make User define functions or Cursors or loop but there is a really very simple way to do this in a simple select statement.

See the below query

DECLARE @Users varchar(MAX)
SET @Users = ''
SELECT @Users = @Users + CONVERT(NVARCHAR(50),firstname) + ','
FROM UserDetails
SET @Users = LEFT(@Users,LEN(@Users)-1)
SELECT @Users as users

Sending email in ASP.NET 2.0

System.Net.Mail namespace provides classes to send email. To send email, we need to create object of MailMessage class and set its properties. Then create instance of SmtpClient class and send email by calling SmtpClient class send method which accepts MailMessage object as its argument.

The SMTP server information used by the SmtpClient class can be specified programmatically, through the SmtpClient class’s properties, or can be specified in Web.config file. To use the Web.config approach, we need to add <> element within the <configuration> element. Then, add a <mailSettings> element that contains an <smtp> element whose settings are specified within its <network> child element, as below.

<!-- Add the email settings to the <> element -->
password="password" />

Dim ToAddress As String = ""
Dim FromAddress As String = ""
Dim mm As New MailMessage(FromAddress, ToAddress)
mm.Subject = "Mail Subject"
mm.Body = "Mail Body"
mm.IsBodyHtml = True
Dim smtp As New SmtpClient

Datetime range in sql server

Hi All,

This is very useful when we search data in sql with datetime parameter. Sometimes we required data from sql within date range then it will consider time also and gives some wrong output. Now I am presenting a simple query through you can compare only date portion. This is very useful when we use sql server 2005 because beyond that version, if we talking about the sql server 2008 then it will provide us date datatype. So we can compare it easily. Currently I am talking about datetime datatype.

select * from <table>
where @fromDate >= dateadd(day, datediff(day, 0, @fromDate), 0);
and @toDate <= dateadd(day, datediff(day, 0, @toDate), 0);


Generate full qualified URL in (

Sometimes in ASP.Net we need to generate emails which contains links back to the website. This links have to be absolute URL in order to work. For this we need to turn the relative URL into absolute URL.

One way is we can hardcode the domain name in URL while generating absolute URL. For eg. + relative URL. But this will cause problem when domain name is changed. It also causes problem because ASP.Net application has different URLs depending on the environment. In development environment URL might be http://localhost:portno/products/editproduct.aspx?id=23.

Generating full qualified URL in ASP.Net is simple. The following code will build the URL by correct protocol(HTTP or HTTPS), correct server name ( or localhost or localhost:453 or IP address) and application path.

string relativeUrl = "~/Products/EditProduct.aspx?id=" + id;
string fullyQualifiedUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl(relativeUrl);

Request.Url.GetLeftPart(UriPartial.Authority) method will return protocol and domain name part of the URL. ie.

STUFF function in sql

Hello All,

Today we discuss STUFF function in sql. It is use to inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position. For Example,

Select stuff('1666678', 2, 3, '2345')

Output : 12345678

Convert Linq result to DataTable

Hello All,

Once I am stuck in LINQ query result, I need result as datatable but I didn’t find any linq method which directly converts result into datatable. So I have made one function which is used for converting linq result into datatable.

Please see the below method which is used for converting linq result set to datatable.

private DataTable AsDataTable<T>(IEnumerable<T> enumberable, string dtName)
   DataTable table = new DataTable(dtName);

   T first = enumberable.FirstOrDefault();
   if (first == null)
   return table;

   PropertyInfo[] properties = first.GetType().GetProperties();
   foreach (PropertyInfo pi in properties)
   table.Columns.Add(pi.Name, pi.PropertyType);

   foreach (T t in enumberable)
      DataRow row = table.NewRow();
      foreach (PropertyInfo pi in properties)
      row[pi.Name] = t.GetType().InvokeMember(pi.Name, BindingFlags.GetProperty, null, t, null);
   return table;

Now see the below code which is used above function to convert linq result to datatable.

IList<Object> data = new List<Object>();
data.Add(new { Name="Nikunj", ID="1", isFuturePay=true});
data.Add(new { Name = "Amit", ID = "2", isFuturePay = false });
data.Add(new { Name = "Raj", ID = "3", isFuturePay = true });
data.Add(new { Name = "Jaimin", ID = "4", isFuturePay = false });

DataTable table = AsDataTable((from d in data
select d), "CancelledError");

Page Life Cycle in ASP.NET

Hi All,

This article is very useful for beginners. When a web page is sent to the Web Server for processing, it goes through a sequence of steps before it finally gets displayed in the Web Browser.

The sequence of events that takes place in the life cycle of a web page in ASP.NET is:

ProcessPostData (Second Time)
Raise ChangedEvents
Raise PostBackEvent

How to delete duplicate records ?

Hello Everyone,

Sometimes we encounter a problem in sql table to delete duplicate records (eg there are 3 similar records, only 2 have to be deleted) and we need a SQL query for this.
This is a common problem so I thought I’d provide some solutions for this problem.

If table contains primary key then you can delete duplicate records by using below sql query.

DELETE FROM TableName WHERE PrimaryColumn NOT IN
(SELECT MIN(PrimaryColumn) FROM TABLENAME GROUP BY DuplicateColumnName)

If table doesn’t contains primary key then you can delete it easily by using following method.
The simplest way to delete the duplicate records is to SELECT DISTINCT into a temporary table, truncate the original table and SELECT the records back into the original table.

You can also delete it by using below query.

With temptable as
SELECT ROW_NUMBER() over (PARTITION BY DuplicateColumnName,DuplicateColumnName ORDER BY DuplicateColumnName,DuplicateColumnName) AS rownumber,* FROM TableName
DELETE FROM temptable WHERE rownumber > 1