格式化零开头的字符串';s

本文关键字:字符串 开头 格式化 | 更新日期: 2023-09-27 18:26:42

我正在尝试将一个对象(来自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();
            }

所以我想知道是否有人能发现我做错了什么,或者他们能帮助我找到正确的方法。

格式化零开头的字符串';s

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

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

最后一行应该是

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
}

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

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

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