|
-
March 9th, 2011, 11:08 PM
#1
[RESOLVED] Why can't I format a decimal into a string?
I need to be able to format a decimal into a string with a specified number of decimal places.
Here is my simple test page code consisting of a a text box, a button and a label. The idea is for the user to enter a decimal number, i.e., 23.345456, then click the button and have the label show the formatted decimal string. But try as I may, I cannot get it to work.
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DecimalFormat.aspx.cs" Inherits="DecimalFormat" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.style1
{
font-size: large;
color: #000080;
font-weight: bold;
font-family: Arial, Helvetica, sans-serif;
}
.style2
{
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: medium;
color: #000080;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<p class="style1">
TEST DECIMAL FORMAT USING C#</p>
<div>
<span class="style2">Enter Decimal</span> :<asp:TextBox ID="txtBoxDecimal"
runat="server"></asp:TextBox>
<br />
</div>
<asp:Button ID="btnFormat" runat="server" Text="Format"
onclick="btnFormat_Click" />
<asp:Label ID="labelDecimal" runat="server" Font-Bold="True" Font-Names="Arial"
Font-Size="Medium"></asp:Label>
</form>
</body>
</html>
And here is the underlying C# code:
Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization; // NumberFormatInfo class
public partial class DecimalFormat : System.Web.UI.Page
{
public String sDecimal;
public Decimal decnum;
protected void Page_Load(object sender, EventArgs e)
{
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberDecimalDigits = 3;
//sDecimal = txtBoxDecimal.ToString();
sDecimal = txtBoxDecimal.Text;
// decnum = txtBoxDecimal.
decnum = Convert.ToDecimal(sDecimal, nfi);
}
protected void btnFormat_Click(object sender, EventArgs e)
{
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberDecimalDigits = 0;
String sFormatDecimal = Convert.ToString(decnum, nfi);
labelDecimal.Text = sFormatDecimal;
}
}
Appreciate info on how to do this correctly. Thanks.
mpliam
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|