使用LEading Zero的格式化字符串

时间:2013-08-07 15:00:49

标签: c# formatting

我正在尝试将对象(来自SQL服务器)转换为整数,因此我可以将数字格式化为在其前面具有正确的零数量。

例如:

如果我 25.6 ,我需要 0025.6

现在我已经在网上看过如何做到这一点,但是我看过人们发布的方法并不适合我。我不完全确定为什么。我正在尝试格式化GlobalVariables.grossweightafter。我从SQL服务器读取了值GlobalVariables.grossweight,但是当它TryParse时,它就失去了它的值。我的代码如下:

            while (TransferRecord.Read())
            {
                //Pulling data from the SQL server. getting data for every line of code as specified.
                GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
                GlobalVariables.baleline = TransferRecord["pulp_line_id"];
                GlobalVariables.baleid = TransferRecord["bale_id"];
                GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
                GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
                GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
                GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];

                //Converting the date, and the baleid to fit in the string.
                DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
                int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);

                int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
                GlobalVariables.grossweightafter.ToString("0000.0");
                //Calling the WriteData method.
                WriteData();
            }

所以我想知道是否有人能抓住我做错了什么,或者他们可以帮助我找到正确的方法来解决这个问题。

3 个答案:

答案 0 :(得分:2)

@Hans Passant所说的是你需要分配从.ToString返回的值。该行应该是:

GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");

答案 1 :(得分:2)

最后一行应该是

if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
    string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
    //you need to save the string returned from the ToString-method somewhere or it will be lost.
    ///Alternatively, if GlobalVariables can contain strings aswell:
    GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
    //React on value not being an int
}

答案 2 :(得分:1)

也许您应该尝试使用double.TryParse()方法而不是int.TryParse(),因为int没有小数部分?

此外,您需要将ToString()结果存储到字符串变量中。你的代码应该是这样的:

GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");