格式化数据表中的字符串时出现问题
我将一个数值保存到数据表单元格中(尚未明确声明该单元格的数据类型),然后检索该数据并尝试将其格式化为字符串。问题是我尝试过的任何方法都无法正确格式化字符串。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))
String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))
可能不是最优雅的解决方案,但您可以从字符串的尾部(或从小数点)向后迭代,每三个字符添加一个逗号,直到用完为止。
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.
为您想要执行的操作提供更多上下文可能会有所帮助,但这里有一个从 DataTable 中获取值然后根据需要对其进行格式化的示例。
在调用 ToString 之前,我显式地将值转换回双精度值。您还可以对该值调用 string.Format 而不是 ToString,它应该也能正常工作。
编辑:如果您将值存储为字符串,然后想要对其进行格式化,请使用以下命令:
这确实假设该值是可解析的(即不为空)。
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.
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:
This does assume that the value is parsable though (i.e. isn't null).
这些方法的问题在于,根据基础表的结构,该字段可能为空。如果您尝试将作为对象(在数据表中)保存的空值转换为字符串、整数、小数或您拥有的其他值...您的应用程序将 100% 崩溃。除非您的数据集是强类型数据集,否则您将始终需要执行此错误检查。事实上,编写一个小型数据读取类来读取字符串、小数、日期时间、整数等等……在任何与数据库有关的数据访问操作中都是必须的……
所以这里有更多的防错功能理想情况下应该将其包装在辅助方法中,如下所示:
传递“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:
passing "N" or "{0:0,0}" as the format string will work just fine.