格式化数据表中的字符串时出现问题

发布于 2024-11-07 08:26:10 字数 306 浏览 0 评论 0原文

我将一个数值保存到数据表单元格中(尚未明确声明该单元格的数据类型),然后检索该数据并尝试将其格式化为字符串。问题是我尝试过的任何方法都无法正确格式化字符串。

50000 --> 50,000

(其中 r 是循环中的行):

String.Format("{0:0,0}", r["columnName"])

r["columnName"].ToString("n0")

还有几种变化,但没有任何运气。大多数时候我只得到不带逗号的数字。

I'm saving a numeric value into a datatable cell (no datatype for the cell has been explicitly declared), then later retrieving that data and trying to format it into a string. Problem is that nothing I've tried will properly format the string.

50000 --> 50,000

I've tried (where r is the row in a loop):

String.Format("{0:0,0}", r["columnName"])

r["columnName"].ToString("n0")

And several variations without any luck. Most of the time I just get the number without the comma.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏夜暖风 2024-11-14 08:26:10

String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))

String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))

遇到 2024-11-14 08:26:10

可能不是最优雅的解决方案,但您可以从字符串的尾部(或从小数点)向后迭代,每三个字符添加一个逗号,直到用完为止。

Probably not the most elegant solution, but you could just iterate backwards from the tail-end of the string (or from the decimal point) adding a comma every three characters until you run out.

清秋悲枫 2024-11-14 08:26:10

为您想要执行的操作提供更多上下文可能会有所帮助,但这里有一个从 DataTable 中获取值然后根据需要对其进行格式化的示例。

DataTable dt = new DataTable();
dt.Columns.Add( "cellName", typeof( double ) );
dt.Rows.Add( 123.45 );
string val = ( (double)dt.Rows[0]["cellName"] ).ToString( "N" ); // val = "123.45"

在调用 ToString 之前,我显式地将值转换回双精度值。您还可以对该值调用 string.Format 而不是 ToString,它应该也能正常工作。

编辑:如果您将值存储为字符串,然后想要对其进行格式化,请使用以下命令:

string val = ( double.Parse( dt.Rows[0]["cellName"] ) ).ToString( "N" );

这确实假设该值是可解析的(即不为空)。

It might be helpful to have more context for what you're trying to do, but here is an example of getting a value out of a DataTable and then formatting it as desired.

DataTable dt = new DataTable();
dt.Columns.Add( "cellName", typeof( double ) );
dt.Rows.Add( 123.45 );
string val = ( (double)dt.Rows[0]["cellName"] ).ToString( "N" ); // val = "123.45"

I'm explicitly casting the value back to a double before calling ToString. You could also call string.Format on that value instead of ToString and it should work just as well.

EDIT: If you're storing the value as a string and then want to format it, use this:

string val = ( double.Parse( dt.Rows[0]["cellName"] ) ).ToString( "N" );

This does assume that the value is parsable though (i.e. isn't null).

酷遇一生 2024-11-14 08:26:10

这些方法的问题在于,根据基础表的结构,该字段可能为空。如果您尝试将作为对象(在数据表中)保存的空值转换为字符串、整数、小数或您拥有的其他值...您的应用程序将 100% 崩溃。除非您的数据集是强类型数据集,否则您将始终需要执行此错误检查。事实上,编写一个小型数据读取类来读取字符串、小数、日期时间、整数等等……在任何与数据库有关的数据访问操作中都是必须的……

所以这里有更多的防错功能理想情况下应该将其包装在辅助方法中,如下所示:

public static string GetFormatedDecimalString(DataRow row, string columnName, string format)
{

    string ColumnNameStringValue = String.Empty;
    decimal ColumnNameValue = Decimal.Zero;

    if( row[columnName) == DBNull.Value )
    {
        ColumnNameValue = Decimal.Zero;
    }
    else
    {
        ColumnNameStringValue = row[columnName].ToString();

        if( ! Decimal.TryParse(ColumnNameStringValue, out ColumnNameValue )
        {
           ColumnNameValue = Decimal.Zero;
        }

        // if the if statement evaluated to false the ColumnNameValue will have the right
        // number you are looking for.
    }

    return ColumnNameValue.ToString(format);
}

传递“N”或“{0:0,0}”作为格式字符串就可以了。

The problem with these methods is that depending on the structure of the underlying table that field may be null. If you try to cast a null value held as an object (in the DataTable) to string,integer, decimal, or what have you... your app will blow up 100% of the time. Unless your DataSet is a strongly typed data set you will always want to do this error checking. As a matter of fact, writing a small data reading class to read string, decimals, date times, integers, whatever... is a must in any Data access operations having to do with Database....

So here is more error proof approach which idealy should be wrapped in a helper method as shown here:

public static string GetFormatedDecimalString(DataRow row, string columnName, string format)
{

    string ColumnNameStringValue = String.Empty;
    decimal ColumnNameValue = Decimal.Zero;

    if( row[columnName) == DBNull.Value )
    {
        ColumnNameValue = Decimal.Zero;
    }
    else
    {
        ColumnNameStringValue = row[columnName].ToString();

        if( ! Decimal.TryParse(ColumnNameStringValue, out ColumnNameValue )
        {
           ColumnNameValue = Decimal.Zero;
        }

        // if the if statement evaluated to false the ColumnNameValue will have the right
        // number you are looking for.
    }

    return ColumnNameValue.ToString(format);
}

passing "N" or "{0:0,0}" as the format string will work just fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文