Wednesday, July 4, 2007

How to format float numbers in C#.NET and SQL

Hey

Here is the tip to Formatting Float numbers and strings in C#.NET and SQL, Its useful those who are all handling numbers


double Doublevalue = 1234.5667;
Response.Write("Sandard Format :" + Doublevalue);
Response.Write("Currency Format :" + Doublevalue.ToString("C"));
Response.Write("ExponentialFormat :" + Doublevalue.ToString("E") );
Response.Write("Fixed point Format :" + Doublevalue.ToString("F3"));
Response.Write("Number Format to 2 Decimal places :" + Doublevalue.ToString("N2") );
Response.Write("Number Format to 3 Decimal places :" + Doublevalue.ToString("N3") );
Response.Write("General Format :" + Doublevalue.ToString("G") );
Response.Write("Percentage Format :" + Doublevalue.ToString("P1") );



When you bind data use the following in aspx page.

<%#Eval("Doublevalue","{0:F2}")%>

# Eval("AMOUNT","{0:F2}")

to know more on numbers and string formats,


http://www.codeproject.com/books/0672325802.asp

In SQL,

Use the ROUND function,


SELECT ROUND(123.4545, 2) Result ------> 123.4500

SELECT ROUND(123.45, -2) Result -------> 100.00

SELECT ROUND(150.75, 0) Result --------> 151.00

SELECT ROUND(150.75, 0, 1) Result --------> 150.00


ROUND(748.58, -4) Result ------> 0


ROUND(748.58, -1) Result -------> 750.00


ROUND(748.58, -2) Result --------> 700.00


ROUND(748.58, -3) Result ---------> 1000.00

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3) Result ----> 123.9990 124.0000

1 comment:

  1. You can use also zero placeholders, e.g.

    double num = 123.456;
    num.ToString("{0.00}"); // output is "123.46"

    It's better to use static method String.Format instead of using double.ToString():

    String.Format("number with two decimal places: {0:0.00}", num);

    See this article for more information how to use String.Format for float numbers in C#.

    ReplyDelete