显示带前导零的数字文本框值

时间:2014-02-27 10:10:29

标签: c#

我有3个文本框值:

no of requests = 2
court fee = 60
claim amount = 200

我的客户要求他们希望展示:

no of requests = 00002; // 5 characters
court fee = 000006000; // 9 characters
claim amount = 0000020000; // 10 characters

我试过这个,但没有得到这些值。我不知道我哪里出错了。

decimal requests = 0;
decimal CFee = 0;
decimal CLAIMAMT = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    CFee += Convert.ToDecimal(dataGridView1.Rows[i].Cells["CFee"].Value) / 100 * dataGridView1.RowCount;
    CLAIMAMT += Convert.ToDecimal(dataGridView1.Rows[i].Cells["CLAIMAMT"].Value) / 100 ;
    requests = Convert.ToInt16(dataGridView1.RowCount.ToString());
}

textBox3.Text = CFee.ToString();//court fee
textBox4.Text = CLAIMAMT.ToString();//claim amoiunt
textBox2.Text = requests.ToString();//no 

7 个答案:

答案 0 :(得分:9)

不要对整数使用小数。使用int表示整数,小数表示货币金额等。如果你想要前导零,那么你可以这样做:

var str = number.ToString("00000"); // At least five digits with leading zeroes if required.

答案 1 :(得分:4)

您可以尝试使用String.Format

例如,要在数字前添加零,请使用冒号分隔符 :并根据需要写入多个零。

String.Format("{0:00000}", 2);          // "00002"
String.Format("{0:D5}", 2);             // "00002"
String.Format("{0:D9}", 6000);          // "000006000"

答案 2 :(得分:3)

尝试使用PadLeft方法。它将在字符串左侧追加指定的字符,直到达到第一个参数中给出的长度。

textBox3.Text = CFee.ToString().PadLeft(5, '0');

答案 3 :(得分:1)

尝试这样的事情;

string request = "2";
            while (request.Length < 5)
                request = "0" + request;

            string fee = "60";
            for (int i = 0; i < 5; i++)
                fee = "0" + fee;
            while (fee.Length < 9)
                fee += "0";

            string claim = "200";
            for (int i = 0; i < 5; i++)
                claim = "0" + claim;
            while (claim.Length < 10)
                claim += "0";

这正是您的期望: 输出

“00002”

“000006000”

“0000020000”

答案 4 :(得分:1)

为什么不像这样使用String.Format()?

myTextbox.Text = String.Format("{0:000000}", 2);

答案 5 :(得分:1)

您可以将ToStringD格式说明符一起使用:

decimal noOfRequests = 2;
decimal courtFee = 60;
decimal claimAmount = 200;

int noOfRequestsInt = Convert.ToInt32(noOfRequests);
int courtFeeInt = Convert.ToInt32(courtFee);
int claimAmountInt = Convert.ToInt32(claimAmount);

string requests = noOfRequestsInt.ToString("D5");   // output: 00002
string fee = courtFeeInt.ToString("D9");            // output: 000000060
string amount = claimAmountInt.ToString("D10");     // output: 0000000200

http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#DFormatString

答案 6 :(得分:0)

以下代码适用于XAML。 Text =“{Binding Path = DailyPushTimeHour,StringFormat = {0:00}}”