我花了很多时间试图弄清楚数字在 C# 中的不同文化中是如何工作的。除了向数据表添加数字之外,我已经对所有场景进行了排序。在数据库中,我有美国格式的数字(例如1.32),在前端,如果文化是德语,那么它在网格中显示1,32。
我可以使用将 1.32 转换为 1,32,
Convert.ToDouble("1.32").ToString(Culture.GetCultureInfo("de-DE"))
但是当我将其添加到数据表中 double 类型的列中时,它会变成 132.0。
db 中的数字是 double 类型。这就是我尝试将其转换为正确的区域性格式的方法:
dt.Rows.Add(new Object[] { Convert.ToDecimal(ds.Tables[0].Rows[i][5]).ToString(culture.NumberFormat) })
一种方法是格式化网格的 rowdatabound 事件中的数字,但这是否是正确的解决方案?应该有一种方法在数据表中存储文化特定数字。
I have spent so much time trying to figure out how numbers work in different cultures in C#. I have sorted all the scenarios except when adding a number to datatable. In db I have number in US format (e.g. 1.32), in frontend if the culture is german then it show 1,32 in grid.
I can convert 1.32 to 1,32 using
Convert.ToDouble("1.32").ToString(Culture.GetCultureInfo("de-DE"))
but when I add this into a data table in a column of type double it becomes 132.0.
the number in db is of type double. This is how I try to convert it into proper culture format:
dt.Rows.Add(new Object[] { Convert.ToDecimal(ds.Tables[0].Rows[i][5]).ToString(culture.NumberFormat) })
One way would be to format the number in rowdatabound event of grid but is this a proper solution? There should be a way to store culture specific number in datatable.
发布评论
评论(2)
当您将值保存到数据库/数据表时,它应该是双精度类型而不是字符串类型。双精度值不关心格式,仅在将其转换(并显示)为字符串时才关心。
至于格式设置,GridView 使用 CultureInfo.CurrentCulture(可以从代码中更改)。但您也可以使用属性 数据格式字符串
When you save the value to the database/datatable it should be of type double not string. A double value does not care about formatting, only when it is converted (and displayed) as a string.
As for formatting goes, the GridView uses the culture specified in CultureInfo.CurrentCulture (can be changed from code). But you can also set you specific formatting on BoundField using property DataFormatString
如果您尝试将字符串添加到 double 类型的 DataTable 字段,它将使用
CultureInfo.CurrentCulture
进行解析 - 在您的情况下,它可能以句点作为小数分隔符。您应该将 double 直接添加到 DataTable,而不是将其格式化为不同区域性 (de-DE) 中的字符串:
而不是:
随后您可以更改用于显示 DataTable 中的值的区域性 - 如何执行此操作取决于关于如何显示它,但一种方法是:
If you attempt to add a string to a DataTable field of type double, it will be parsed using the
CultureInfo.CurrentCulture
- which presumably has period as a decimal separator in your case.You should add the double directly to the DataTable, rather than formatting it as a string in a different culture (de-DE):
rather than:
Subsequently you can change the culture used to display the value from the DataTable - how you do this depends on how you are displaying it, but one way is: