[ASP.NET]數字格式

  • 21545
  • 0

[ASP.NET]數字格式

通常在C#或VB.NET裡面,要對數字做四捨五入,甚至加上三位一撇的格式,

我們會使用string.Format()來幫忙做轉換。

 

但是,符合四捨五入位數,且數字加上三位一撇格式的有兩種寫法,這邊針對型態為decimal的數字字串,來進行格式化。

讓大家知道兩種pattern的差異。總共四組label跟textbox,來說明碰上不同數字,使用不同的pattern最後的差異。

aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NumFormat.aspx.cs" Inherits="NumFormat" %>

<!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>未命名頁面</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="1230.456789用{0:N4}"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="1230用{0:N4}"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="1230.456789用{0:#,0.####}"></asp:Label>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label4" runat="server" Text="1230用{0:#,0.####}"></asp:Label>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class NumFormat : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string a = "1230.456789";
        string b = "1230";
        //string b = a.ToString("#.####");{0:#,0.#########}
        string c1 = string.Empty;
        string c2 = string.Empty;
        string d1 = string.Empty;
        string d2 = string.Empty;
        c1 = string.Format("{0:N4}", Convert.ToDecimal(a));
        c2 = string.Format("{0:N4}", Convert.ToDecimal(b));
        d1 = string.Format("{0:#,0.####}", Convert.ToDecimal(a));
        d2 = string.Format("{0:#,0.####}", Convert.ToDecimal(b));
        this.TextBox1.Text = c1;
        this.TextBox2.Text = c2;
        this.TextBox3.Text = d1;
        this.TextBox4.Text = d2;
    }
}

出來的結果:

數字格式轉換三位一撇

大家可以看到最大的差異,

就在”{0:N4}”不論怎樣,都會有小數四位,即使是整數,也會補四位小數0。

而在”{0:#,0.####}”則是超過四位小數,則四捨五入至小數第四位,不到四位小數,則不補0。

專案開發上,兩種情況都還蠻常遇到的,這邊隨筆記錄一下,不然下次又要翻很久了。

後記:補上如何將字串轉回需要的數值,一樣舉例decimal。

decimal val=decimal .Parse("65,536.1234", System.Globalization.NumberStyles.Number);

 


blog 與課程更新內容,請前往新站位置:http://tdd.best/